Why Programming Languages Are Called Object Oriented
7.3 Exploring String Methods
Strings are central to programming; almost every program uses strings in some way. We’ll explore some of the ways in which we can manipulate strings and, at the same time, firm up our understanding of methods.
The most commonly used string methods are listed in Table 7, Common String Methods. (You can find the complete list in Python’s online documentation, or type help(str) into the shell.)
Description Method
Returns a copy of the string with the first letter capi-talized and the rest lowercase
str.capitalize()
Returns the number of nonoverlapping occurrences of s in the string
str.count(s)
Returns True iff the string ends with the characters in the end string—this is case sensitive.
str.endswith(end)
Returns the index of the first occurrence of s in the string, or -1 if s doesn’t occur in the string—the first character is at index 0. This is case sensitive.
str.find(s)
Returns the index of the first occurrence of s at or after index beg in the string, or -1 if s doesn’t occur in str.find(s, beg)
the string at or after index beg—the first character is at index 0. This is case sensitive.
Returns the index of the first occurrence of s between indices beg (inclusive) and end (exclusive) in the string, str.find(s, beg, end)
or -1 if s does not occur in the string between indices beg and end—the first character is at index 0. This is case sensitive.
Returns a string made by substituting for placeholder fields in the string—each field is a pair of braces str.format(«expressions»)
('{' and '}') with an integer in between; the expression arguments are numbered from left to right starting
Description Method
at 0. Each field is replaced by the value produced by evaluating the expression whose index corresponds with the integer in between the braces of the field. If an expression produces a value that isn’t a string, that value is converted into a string.
Returns True iff all characters in the string are lowercase
str.islower()
Returns True iff all characters in the string are uppercase
str.isupper()
Returns a copy of the string with all letters converted to lowercase
str.lower()
Returns a copy of the string with leading whitespace removed
str.lstrip()
Returns a copy of the string with leading occurrences of the characters in s removed
str.lstrip(s)
Returns a copy of the string with all occurrences of substring old replaced with string new
str.replace(old, new)
Returns a copy of the string with trailing whitespace removed
str.rstrip()
Returns a copy of the string with trailing occurrences of the characters in s removed
str.rstrip(s)
Returns the whitespace-separated words in the string as a list (We’ll introduce the list type in Section 8.1, Storing and Accessing Data in Lists, on page 129.) str.split()
Returns True iff the string starts with the letters in the string beginning—this is case sensitive.
str.startswith(beginning)
Returns a copy of the string with leading and trailing whitespace removed
str.strip()
Returns a copy of the string with leading and trailing occurrences of the characters in s removed
str.strip(s)
Returns a copy of the string with all lowercase letters capitalized and all uppercase letters made lowercase str.swapcase()
Returns a copy of the string with all letters converted to uppercase
str.upper()
Table 7—Common String Methods
Chapter 7. Using Methods
•
120Method calls look almost the same as function calls, except that in order to call a method we need an object of the type associated with that method. For example, let’s call the method startswith on the string 'species':
>>> 'species'.startswith('a')
False
>>> 'species'.startswith('spe')
True
String method startswith takes a string argument and returns a bool indicating whether the string whose method was called—the one to the left of the dot—starts with the string that is given as an argument. There is also an endswith method:
>>> 'species'.endswith('a')
False
>>> 'species'.endswith('es')
True
Sometimes strings have extra whitespace at the beginning and the end. The string methods lstrip, rstrip, and strip remove this whitespace from the front, from the end, and from both, respectively. This example shows the result of applying these three functions to a string with leading and trailing whitespace:
>>> compound = ' \n Methyl \n butanol \n'
>>> compound.lstrip()
'Methyl \n butanol \n'
>>> compound.rstrip()
' \n Methyl \n butanol'
>>> compound.strip()
'Methyl \n butanol'
Note that the other whitespace inside the string is unaffected; these methods only work from the front and end. Here is another example that uses string method swapcase to change lowercase letters to uppercase and uppercase to lowercase:
>>> 'Computer Science'.swapcase()
'cOMPUTER sCIENCE'
String method format has a complex description, but a couple of examples should clear up the confusion. Here we show that we can substitute a series of strings into a format string:
>>> '"{0}" is derived from "{1}"'.format('none', 'no one')
'"none" is derived from "no one"'
>>> '"{0}" is derived from the {1} "{2}"'.format('Etymology', 'Greek',
... 'ethos')
'"Etymology" is derived from the Greek "ethos"'
>>> '"{0}" is derived from the {2} "{1}"'.format('December', 'decem', 'Latin')
'"December" is derived from the Latin "decem"'
We can have any number of fields. The last example shows that we don’t have to use the numbers in order.
Next, using string method format, we’ll specify the number of decimal places to round a number to. We indicate this by following the field number with a colon and then using .2f to state that the number should be formatted as a floating-point number with two digits to the right of the decimal point:
>>> my_pi = 3.14159
>>> 'Pi rounded to {0} decimal places is {1:.2f}.'.format(2, my_pi)
'Pi rounded to 2 decimal places is 3.14.'
>>> 'Pi rounded to {0} decimal places is {1:.3f}.'.format(3, my_pi)
'Pi rounded to 3 decimal places is 3.142.'
It’s possible to omit the position numbers. If that’s done, then the arguments passed to format replace each placeholder field in order from left to right:
>>> 'Pi rounded to {} decimal places is {:.3f}.'.format(3, my_pi)
'Pi rounded to 3 decimal places is 3.142.'
Remember how a method call starts with an expression? Because 'Computer Science'.swapcase() is an expression, we can immediately call method endswith on the result of that expression to check whether that result has 'ENCE' as its last four characters:
>>> 'Computer Science'.swapcase().endswith('ENCE')
True
Figure 8, Chaining Method Calls, gives a picture of what happens when we do this:
'Computer Science'.swapcase().endswith('ENCE')
.endswith('ENCE') 'cOMPUTER sCIENCE'
True Figure 8—Chaining Method Calls
The call on method swapcase produces a new string, and that new string is used for the call on method endswith.
Both int and float are classes. It is possible to access the documentation for these either by calling help(int) or by calling help on an object of the class:
Chapter 7. Using Methods
•
122>>> help(0)
Help on int object:
class int(object)
| int(x[, base]) -> integer
|
| Convert a string or number to an integer, if possible. A floating
| point argument will be truncated towards zero (this does not include a
| string representation of a floating point number!) When converting a
| string, use the optional base. It is an error to supply a base when
| converting a non-string.
Most modern programming languages are structured this way: the “things”
in the program are objects, and most of the code in the program consists of methods that use the data stored in those objects. Chapter 14, Object-Oriented Programming, on page 269, will show you how to create new kinds of objects;
until then, we’ll work with objects of types that are built into Python.