Pages

Wednesday, July 7, 2010

More about Strings


We have already discussed strings in detail earlier. What more can there be to know? Well, did you
know that strings are also objects and have methods which do everything from checking part of a string
to stripping spaces!
The strings that you use in program are all objects of the class str. Some useful methods of this class
are demonstrated in the next example. For a complete list of such methods, see help(str).
String Methods
Example 9.7. String Methods
#!/usr/bin/python
# Filename: str_methods.py
name = 'Swaroop' # This is a string object
if name.startswith('Swa'):
print 'Yes, the string starts with "Swa"'
if 'a' in name:
print 'Yes, it contains the string "a"'
if name.find('war') != -1:
print 'Yes, it contains the string "war"'
delimiter = '_*_'
mylist = ['Brazil', 'Russia', 'India', 'China']
print delimiter.join(mylist)
Output
$ python str_methods.py
Yes, the string starts with "Swa"
Yes, it contains the string "a"
Yes, it contains the string "war"
Brazil_*_Russia_*_India_*_China
How It Works
Here, we see a lot of the string methods in action. The startswith method is used to find out whether
the string starts with the given string. The in operator is used to check if a given string is a part of the
string.
The find method is used to do find the position of the given string in the string or returns -1 if it is not
successful to find the substring. The str class also has a neat method to join the items of a sequence with the string acting as a delimiter between each item of the sequence and returns a bigger string generated
from this.

Objects and References


Example 9.6. Objects and References
#!/usr/bin/python
# Filename: reference.py
print 'Simple Assignment'
shoplist = ['apple', 'mango', 'carrot', 'banana']
mylist = shoplist # mylist is just another name pointing to the same object!
del shoplist[0] # I purchased the first item, so I remove it from the list
print 'shoplist is', shoplist
print 'mylist is', mylist
# notice that both shoplist and mylist both print the same list without
# the 'apple' confirming that they point to the same object
print 'Copy by making a full slice'
mylist = shoplist[:] # make a copy by doing a full slice
del mylist[0] # remove first item
print 'shoplist is', shoplist
print 'mylist is', mylist
# notice that now the two lists are different
Output
$ python reference.py
Simple Assignment
shoplist is ['mango', 'carrot', 'banana']
mylist is ['mango', 'carrot', 'banana']
Copy by making a full slice
shoplist is ['mango', 'carrot', 'banana']
mylist is ['carrot', 'banana']
How It Works
Most of the explanation is available in the comments itself. What you need to remember is that if you
want to make a copy of a list or such kinds of sequences or complex objects (not simple objects such as
integers), then you have to use the slicing operation to make a copy. If you just assign the variable name
to another name, both of them will refer to the same object and this could lead to all sorts of trouble if
you are not careful.
Note for Perl programmers
Remember that an assignment statement for lists does not create a copy. You have to use slicing
operation to make a copy of the sequence.

Sequences


Lists, tuples and strings are examples of sequences, but what are sequences and what is so special about
them? Two of the main features of a sequence is the indexing operation which allows us to fetch a particular
item in the sequence directly and the slicing operation which allows us to retrieve a slice of the
sequence i.e. a part of the sequence.
Using Sequences
Example 9.5. Using Sequences
#!/usr/bin/python
# Filename: seq.py
shoplist = ['apple', 'mango', 'carrot', 'banana']
# Indexing or 'Subscription' operation
print 'Item 0 is', shoplist[0]
print 'Item 1 is', shoplist[1]
print 'Item 2 is', shoplist[2]
print 'Item 3 is', shoplist[3]
print 'Item -1 is', shoplist[-1]
print 'Item -2 is', shoplist[-2]
# Slicing on a list
print 'Item 1 to 3 is', shoplist[1:3]
print 'Item 2 to end is', shoplist[2:]
print 'Item 1 to -1 is', shoplist[1:-1]
print 'Item start to end is', shoplist[:]
# Slicing on a string
name = 'swaroop'
print 'characters 1 to 3 is', name[1:3]
print 'characters 2 to end is', name[2:]
print 'characters 1 to -1 is', name[1:-1]
print 'characters start to end is', name[:]
Output
$ python seq.py
Item 0 is apple
Item 1 is mango
Item 2 is carrot
Item 3 is banana

Item -1 is banana
Item -2 is carrot
Item 1 to 3 is ['mango', 'carrot']
Item 2 to end is ['carrot', 'banana']
Item 1 to -1 is ['mango', 'carrot']
Item start to end is ['apple', 'mango', 'carrot', 'banana']
characters 1 to 3 is wa
characters 2 to end is aroop
characters 1 to -1 is waroo
characters start to end is swaroop
How It Works
First, we see how to use indexes to get individual items of a sequence. This is also referred to as the subscription
operation. Whenever you specify a number to a sequence within square brackets as shown
above, Python will fetch you the item corresponding to that position in the sequence. Remember that Python
starts counting numbers from 0. Hence, shoplist[0] fetches the first item and shoplist[3]
fetches the fourth item in the shoplist sequence.
The index can also be a negative number, in which case, the position is calculated from the end of the
sequence. Therefore, shoplist[-1] refers to the last item in the sequence and shoplist[-2]
fetches the second last item in the sequence.
The slicing operation is used by specifying the name of the sequence followed by an optional pair of
numbers separated by a colon within square brackets. Note that this is very very similar to the indexing
operation you have been using til lnow. Remember the numbers are optional but the colon isn't.
The first number (before the colon) in the slicing operation refers to the position from where the slice
starts and the second number (after the colon) indicates where the slice will stop at. If the first number is
not specified, Python will start at the beginning of the sequence. If the second number is left out, Python
will stop at the end of the sequence. Note that the slice returned starts at the start position and will end
just before the end position i.e. the start position is included but the end position is excluded from the sequence
slice.
Thus, shoplist[1:3] returns a slice of the sequence starting at position 1, includes position 2 but
stops at position 3 and therefore a slice of two items is returned. Similarly, shoplist[:] returns a
copy of the whole sequence.
You can also do slicing with negative positions. Negative numbers are used for positions from the end of
the sequence. For example, shoplist[:-1] will return a slice of the sequence which excludes the
last item of the sequence but contains everything else.
Try various combinations of such slice specifications using the Python interpreter interactively i.e. the
prompt so that you can see the results immediately. The great thing about sequences is that you can access
tuples, lists and strings all in the same way!