More About Strings


A Byte of Python 

Go to the Table of Contents. Visit the Gifcom web site.

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.

Summary

We have explored the various built-in data structures of Python in detail. These data structures will be essential for writing programs of reasonable size.

Now that we have a lot of the basics of Python in place, we will next see how to design and write a real-world Python program.