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.

Listed in Table 8, Common String Methodsare the most commonly used string methods. (You can find the complete list in Python’s online documentation, or type help(str) into the shell.)


Table 8. Common String Methods

Method

Description

str.capitalize()

Returns a copy of the string with the first letter capitalized and the rest lowercase.

str.count(s)

Returns the number of nonoverlapping occurrences of s in the string.

str.endswith(end)

Returns True if and only if the string ends with the characters in the end string—this is case sensitive.

str.find(s)

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, beg)

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 the string at or after index beg—the first character is at index 0. This is case sensitive.

str.find(s, beg, end)

Returns the index of the first occurrence of s between indices beg (inclusive) and end (exclusive) in the string, 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.

str.format(«expressions»)

Returns a string made by substituting for placeholder fields in the string—each field is a pair of braces (’{’ and ’}’) with an integer in between; the expression arguments are numbered from left to right starting 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.

str.islower()

Returns True if and only if all characters in the string are lowercase.

str.isupper()

Returns True if and only if all characters in the string are uppercase.

str.lower()

Returns a copy of the string with all letters converted to lowercase.

str.lstrip()

Returns a copy of the string with leading whitespace removed.

str.lstrip(s)

Returns a copy of the string with leading occurrences of the characters in s removed.

str.replace(old, new)

Returns a copy of the string with all occurrences of substring old replaced with string new.

str.rstrip()

Returns a copy of the string with trailing whitespace removed.

str.rstrip(s)

Returns a copy of the string with trailing occurrences of the characters in s removed.

str.split()

Returns the whitespace-separated words in the string as a list. (We’ll introduce the list type in Storing and Accessing Data in Lists.)

str.startswith(beginning)

Returns True if and only if the string starts with the letters in the string beginning—this is case sensitive.

str.strip()

Returns a copy of the string with leading and trailing whitespace removed.

str.strip(s)

Returns a copy of the string with leading and trailing occurrences of the characters in s removed.

str.swapcase()

Returns a copy of the string with all lowercase letters capitalized and all uppercase letters made lowercase.

str.upper()

Returns a copy of the string with all letters converted to uppercase.


Method 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 methods to a string with leading and trailing whitespace:

 >>>​​ ​​compound​​ ​​=​​ ​​' Methyl butanol '
 >>>​​ ​​compound.lstrip()
 'Methyl butanol '
 >>>​​ ​​compound.rstrip()
 ' Methyl butanol'
 >>>​​ ​​compound.strip()
 'Methyl 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

The next figure shows what happens when we do this:

images/modules/multiple_calls.png

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:

 >>>​​ ​​help(0)
 Help on int object:
 
 class int(object)
  | int(x=0) -> integer
  | int(x, base=10) -> integer
  |
  | Convert a number or string to an integer, or return 0 if no arguments
  | are given. If x is a number, return x.__int__(). For floating point
  | numbers, this truncates towards zero.
  |
  | If x is not a number or if base is given, then x must be a string,
  | bytes, or bytearray instance representing an integer literal in the
  | given base. The literal can be preceded by '+' or '-' and be surrounded
  | by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.
  | Base 0 means to interpret the base from the string as an integer literal.
  | >>> int('0b100', base=0)
  | 4
  |
  | Methods defined here:
  |
  | __abs__(self, /)
  | abs(self)
  |
  | __add__(self, value, /)
  | Return self+value.
  ...

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, will show you how to create new kinds of objects; until then, we’ll work with objects of types that are built into Python.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.255.140