Chapter: Problem Solving and Python Programming : Control Flow, Functions

Strings - Python

A string is a sequence of characters. You can access the characters one at a time with the bracket operator:

STRINGS

 

A string is a sequence of characters. You can access the characters one at a time with the bracket operator:

 

>>>fruit = 'banana'

>>>letter = fruit[1]

 

The second statement selects character number 1 from fruit and assigns it to letter. The expression in brackets is called an index. The index indicates which character in the sequence you want (hence the name). But you might not get what you expect:

 

>>>print letter

a

 

For most people, the first letter of 'banana' is b, not a. But for computer scientists, the index is an offset from the beginning of the string, and the offset of the first letter is zero.

 

>>>letter = fruit[0]

>>>print letter

b

 

So b is the 0th letter (“zero-eth”) of 'banana', a is the 1th letter (“one-eth”), and n is the 2th(“two-eth”) letter.

You can use any expression, including variables and operators, as an index, but the value of the index has to be an integer. Otherwise you get:

 

>>> letter = fruit[1.5]

 

TypeError: string indices must be integers, not float

 

len

len is a built-in function that returns the number of characters in a string:

 

>>>fruit = 'banana'

>>>len(fruit)

6

 

To get the last letter of a string, you might be tempted to try something like this:

 

>>> length = len(fruit)

>>> last = fruit[length]

IndexError: string index out of range

 

The reason for the IndexError is that there is no letter in 'banana' with the index 6. Since we started counting at zero, the six letters are numbered 0 to 5. To get the last character, you have to subtract 1 from length:

 

>>> last = fruit[length-1]

>>> print last

a

 

Alternatively, you can use negative indices, which count backward from the end of the string. The expression fruit[-1] yields the last letter, fruit[-2] yields the second to last, and so on.

 

String slices

 

A segment of a string is called a slice. Selecting a slice is similar to selecting a character:

 

>>>   s = 'Monty Python'

>>>   print s[0:5] Monty

print s[6:12]

Python

 

The operator [n:m] returns the part of the string from the “n-eth” character to the “m-eth” character, including the first but excluding the last. This behavior is counterintuitive, but it might help to imagine the indices pointing between the characters, as in Figure 8.1.

If you omit the first index (before the colon), the slice starts at the beginning of the string.

If you omit the second index, the slice goes to the end of the string:

 

>>> fruit = 'banana'

>>> fruit[:3]

'ban'

>>> fruit[3:]

'ana'

 

If the first index is greater than or equal to the second the result is an empty string, represented by two quotation marks:

 

>>> fruit = 'banana'

fruit[3:3]

 

An empty string contains no characters and has length 0, but other than that, it is the same as any other string.

 

Strings are immutable

 

It is tempting to use the [] operator on the left side of an assignment, with the intention of changing a character in a string. For example:

 

>>> greeting = 'Hello, world!'

>>> greeting[0] = 'J'

TypeError: 'str' object does not support item assignment

 

The “object” in this case is the string and the “item” is the character you tried to assign. For now, an object is the same thing as a value, but we will refine that definition later. An item is one of the values in a sequence.

The reason for the error is that strings are immutable, which means you can’t change an existing string. The best you can do is create a new string that is a variation on the original:

 

>>> greeting = 'Hello, world!'

>>> new_greeting = 'J' + greeting[1:]

>>> print new_greeting

Jello, world!

 

This example concatenates a new first letter onto a slice of greeting. It has no effect on the original string.

 

String methods

 

A method is similar to a function—it takes arguments and returns a value—but the syntax is different. For example, the method upper takes a string and returns a new string with all uppercase letters:

Instead of the function syntax upper(word), it uses the method syntax word.upper().

 

>>> word = 'banana'

>>> new_word =

word.upper()

>>> print new_word

BANANA

 

This form of dot notation specifies the name of the method, upper, and the name of the string to apply the method to, word. The empty parentheses indicate that this method takes no argument.

A method call is called an invocation; in this case, we would say that we are invoking upper on the word.

As it turns out, there is a string method named find that is remarkably similar to the function we wrote:

 

>>>   word = 'banana'

>>>   index = word.find('a')

>>>   print index

1

 

In this example, we invoke find on word and pass the letter we are looking for as a parameter.

Actually, the find method is more general than our function; it can find substrings, not just characters:

 

>>>   word.find('na')

2

 

It can take as a second argument the index where it should start:

 

>>>        word.find('na', 3)

4

 

And as a third argument the index where it should stop:

 

>>>   name = 'bob'

>>>   name.find('b', 1, 2)

-1

 

This search fails because b does not appear in the index range from 1 to 2 (not including 2).

 

String comparison

 

The relational operators work on strings. To see if two strings are equal:

 

if word == 'banana':

print 'All right, bananas.'

 

Other relational operations are useful for putting words in alphabetical order:

 

if word < 'banana':

print 'Your word,' + word + ', comes before banana.'

elif word > 'banana':

print 'Your word,' + word + ', comes after banana.'

else:

print 'All right, bananas.'

 

Python does not handle uppercase and lowercase letters the same way that people do. All the uppercase letters come before all the lowercase letters, so: Your word, Pineapple, comes before banana.

A common way to address this problem is to convert strings to a standard format, such as all lowercase, before performing the comparison. Keep that in mind in case you have to defend yourself against a man armed with a Pineapple.

 

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail
Problem Solving and Python Programming : Control Flow, Functions : Strings - Python |


Privacy Policy, Terms and Conditions, DMCA Policy and Compliant

Copyright © 2018-2024 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.