Go to: Na-Rae Han's home page  

Python 2.7 Tutorial

With Videos by mybringback.com

String Methods Part 1

                          << Previous Tutorial           Next Tutorial >>
On this page: .startswith(), .endswith(), in, .count(), .upper(), .lower(), .capitalize(), .title(), .replace(), and .strip(). Also: stacked application, e.g., .lower().count().

Testing for Substring-hood

.startswith() tests for prefix-hood. When called like x.startswith(y), it returns True if the string x starts with the prefix string y, False otherwise. Examples:
 
>>> 'school'.startswith('s') 
True 
>>> 'school'.startswith('scho') 
True 
>>> 'school'.startswith('k') 
False 
On the flip side, .endswith() tests for suffix-hood. When called like x.endswith(y), it returns True if the string x ends with the specified suffix string y, False otherwise. Examples:
 
>>> 'school'.endswith('ol') 
True 
>>> 'school'.endswith('l') 
True 
>>> 'school'.endswith('ll') 
False 
What about substrings in the middle? Well, strings do not have a designated method, but the versatile in operator can be used here. Because in is not a string METHOD, it uses a different syntax of y in x:
 
>>> 'oo' in 'school' 
True 
>>> 'h' in 'school' 
True 
>>> 'scho' in 'school'                # matches string-initially
True 
>>> 'school' in 'school'              # whole substring
True 
>>> 'k' in 'school' 
False 
>>> 'ee' in 'school' 
False 

Counting Substring

.count() returns the number of occurrences of a given substring. The return value is an integer:
 
>>> 'colorless green ideas sleep furiously'.count('s') 
5 
>>> 'colorless green ideas sleep furiously'.count('ee') 
2

Case Manipulators

.upper() is an uppercasing method. It returns a new string where every character is uppercased. .lower() does the opposite: it returns a new string where every character is lowercased.
 
>>> 'Do not enter'.upper() 
'DO NOT ENTER' 
>>> 'DO NOT ENTER'.lower() 
'do not enter' 
.capitalize() turns only the very first character in the entire string into an uppercase letter, while .title() returns a string where every word starts with an uppercase letter:
 
>>> 'colorless green ideas'.capitalize() 
'Colorless green ideas' 
>>> 'colorless green ideas'.title() 
'Colorless Green Ideas' 

Transforming a String

.replace() takes two parameters. When called like x.replace(y,z), a new string is returned where all instances of y in x are replaced by z.
 
>>> mary = 'Mary had a little lamb'
>>> mary.replace('a', 'xx')
'Mxxry hxxd xx little lxxmb' 
.replace() can be used to delete substrings by specifying the empty string '' as the second parameter:
 
>>> chom = 'Colorless green ideas sleep furiously'
>>> chom.replace('ee', '')
'Colorless grn ideas slp furiously' 
>>> chom.replace(' ', '')
'Colorlessgreenideassleepfuriously' 
Sometimes, strings come in with whitespace characters padded on either end, and you need to remove them. .strip() is the method to use:
 
>>> foo = '  \t hello world\n \n'
>>> print foo
  	 hello world 


>>> foo.strip()
'hello world' 
>>> print foo.strip()
hello world 

Stacked Application

When a string method returns a string type, another string method can be tacked on. Below, .replace() method is called repeatedly in order to remove all "vowel" characters:
 
>>> chom = 'Colorless green ideas sleep furiously'
>>> chom.replace('a', '')
'Colorless green ides sleep furiously' 
>>> chom.replace('a', '').replace('e', '').replace('i', '').replace('o', '').replace('u', '')
'Clrlss grn ds slp frsly' 
In the example below, .count() is used on the output of .lower(). Initially there were only two counts of 'sh' because 'Sh' did not match. After lowering the entire string, 'sh' is matched three times.
 
>>> foo = 'She sells seashells by the seashore'
>>> foo.count('sh')              #'sh' is not matching 'Sh'
2 
>>> foo.lower()
'she sells seashells by the seashore' 
>>> foo.lower().count('sh')      #'Sh' is lowered to 'sh'
3 
The ordering between the two methods is important here. Below, .count() is applied first and then .lower(). This doesn't work, because .count() returns an integer, and .lower() does not work on the integer type.
 
>>> print foo
She sells seashells by the seashore 
>>> foo.count('sh').lower()

Traceback (most recent call last):
  File "", line 1, in 
    foo.count('sh').lower()
AttributeError: 'int' object has no attribute 'lower'