In [ 24 ]: t.capitalize()
Out[24]: ‘This is a string object’
Or you can split it into its single-word components to get a list object of all the words
(more on list objects later):
In [ 25 ]: t.split()
Out[25]: [‘this’, ‘is’, ‘a’, ‘string’, ‘object’]
You can also search for a word and get the position (i.e., index value) of the first letter of
the word back in a successful case:
In [ 26 ]: t.find(‘string’)
Out[26]: 10
If the word is not in the string object, the method returns -1:
In [ 27 ]: t.find(‘Python’)
Out[27]: -1
Replacing characters in a string is a typical task that is easily accomplished with the
replace method:
In [ 28 ]: t.replace(‘ ‘, ‘|’)
Out[28]: ‘this|is|a|string|object’
The stripping of strings — i.e., deletion of certain leading/lagging characters — is also
often necessary:
In [ 29 ]: ‘http://www.python.org’.strip(‘htp:/’)
Out[29]: ‘www.python.org’
Table 4-1 lists a number of helpful methods of the string object.
Table 4-1. Selected string methods
Method Arguments Returns/result
capitalize
()
Copy of the string with first letter capitalized
count
(sub[, start[, end]])
Count of the number of occurrences of substring
decode
([encoding[, errors]])
Decoded version of the string, using encoding (e.g., UTF-8)
encode
([encoding[, errors]])
Encoded version of the string
find
(sub[, start[, end]])
(Lowest) index where substring is found
join
(seq)
Concatenation of strings in sequence seq
replace
(old, new[, count])
Replaces old by new the first count times