Strings are central to programming; almost every program uses strings in some way. You’ll explore some of the ways you can manipulate strings and, at the same time, firm up your understanding of methods.
Listed in Table 4, are the most commonly used string methods. You can find the complete list in Python’s online documentation, or type help(str) into the shell.
If the optional parameters start and end are specified, a method operates on the substring only within that part of the string. The start parameter defines the position where the substring begins, with 0 being the start of the string, and the end parameter defines where the substring ends (the last character of the substring is at end-1). If not specified, the substring begins at the start of the string and goes to the end.
| Method | Description |
|---|---|
| str.capitalize | Returns a capitalized version of the string |
| str.count | Returns the number of nonoverlapping occurrences of substring sub in the string. This method is case-sensitive. |
| str.endswith | Returns True if the string ends with the specified suffix, False otherwise. This method is case-sensitive. |
| str.startswith | Returns True if the string starts with the specified prefix, False otherwise. This method is case-sensitive. |
| str.find | Return the smallest index in the string where substring sub is found. Returns -1 on failure. This method is case-sensitive. |
| str.islower | Returns True if all characters in the string are lowercase and there is at least one cased character in the string. Returns False otherwise |
| str.isupper | Returns True if all characters in the string are uppercase and there is at least one cased character in the string. Returns False otherwise |
| str.isnumeric | Returns True if all characters in the string are numeric and there is at least one character in the string, False otherwise |
| str.lower | Returns a copy of the string converted to lowercase |
| str.upper | Returns a copy of the string converted to uppercase |
| str.swapcase | Returns a copy of the string with all lowercase letters capitalized and all uppercase letters made lowercase |
| str.strip | Returns a copy of the string with leading and trailing whitespace removed. If chars is given and not None, remove characters in chars instead. |
| str.lstrip | Returns a copy of the string with leading whitespace removed. If chars is given and not None, remove characters in chars instead. |
| str.rstrip | Returns a copy of the string with trailing whitespace removed. If chars is given and not None, remove characters in chars instead. |
| str.replace | Returns a copy of the string with all occurrences of substring old replaced by new |
| str.split | Returns the whitespace-separated words in the string as a list. (You’ll see the list type in .) |
Notice that any method that appears to modify a string, such as str.upper or str.strip, instead returns a modified copy of the original string. Python strings are immutable: once created, they are “carved in stone” and cannot be modified.
Predicate Functions | |
|---|---|
| | A regular function (or a method) that returns a Boolean value (True or False) is called a predicate function. Historically, predicate function names start with the prefix is or is_, followed by the property that the function reports. So, the function str.isupper checks if a string is in the uppercase, while its sister function, str.upper, converts the string to uppercase. |
Let’s have a look at some examples. Let’s call the method ’species’.startswith(prefix):
| | >>> 'species'.startswith('a') |
| | False |
| | >>> 'species'.startswith('spe') |
| | True |
The method takes a string argument and returns a bool indicating whether the object 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 whitespace from the front, from the end, and from both ends, respectively. This example shows the result of applying these three methods 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' |
Remember how a method call starts with an expression? Because ’Computer Science’.swapcase() is an expression, you 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 you do this:

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