Python by Swaroop C H - HTML preview

PLEASE NOTE: This is an HTML preview only and some elements such as links or page numbers may be incorrect.
Download the book in PDF, ePub, Kindle for a complete version.

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. Thein 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. Thestr class also has a neat method tojoin 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.