We have already discussed strings in detail earlier. What more can there be to add? Well, did you know that strings are also objects and have methods which do everything from checking substrings to stripping spaces!
The strings that you use in your program are all objects (instances) of the class str. Some useful methods of this class are demonstrated in the following example. For a complete list of such methods, see help(str).
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 = ['India', 'China', 'Finland', 'Brazil'] print delimiter.join(mylist)
$ python str_methods.py Yes, the string starts with "Swa" Yes, it contains the string "a" Yes, it contains the string "war" India-*-China-*-Finland-*-Brazil
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 substring of the string i.e. is part of the string.
The find method is used to do the same thing but it returns -1 when it is unsuccessful and returns the position of the substring when it is successful. The string object also has a neat method called join which is used to put the items of a sequence in a string separated by that string.