'spam = "ham ", +00099'
>>> 'spam = "{0:<5}", {1:+06}'.format('ham', 99)
'spam = "ham ", +00099'
These operations are covered in core language resources such as Learning Python. For
the purposes of this chapter, though, we’re interested in more powerful tools: Python’s
string object methods include a wide variety of text-processing utilities that go above
and beyond string expression operators. We saw some of these in action early on in
Chapter 2, and have been using them ever since. For instance, given an instance str of
the built-in string object type, operations like the following are provided as object
method calls:
str.find(substr)
Performs substring searches
str.replace(old, new)
Performs substring substitutions
str.split(delimiter)
Chops up a string around a delimiter or whitespace
str.join(iterable)
Puts substrings together with delimiters between
str.strip()
Removes leading and trailing whitespace
str.rstrip()
Removes trailing whitespace only, if any
str.rjust(width)
Right-justifies a string in a fixed-width field
str.upper()
Converts to uppercase
str.isupper()
Tests whether the string is uppercase
str.isdigit()
Tests whether the string is all digit characters
str.endswith(substr-or-tuple)
Tests for a substring (or a tuple of alternatives) at the end
str.startswith(substr-or-tuple)
Tests for a substring (or a tuple of alternatives) at the front
This list is representative but partial, and some of these methods take additional op-
tional arguments. For the full list of string methods, run a dir(str) call at the Python
interactive prompt and run help(str.method) on any method for some quick docu-
mentation. The Python library manual and reference books such as Python Pocket Ref-
erence also include an exhaustive list.
String Method Utilities | 1407