String Method Utilities

Python’s string methods include a variety of text-processing utilities that go above and beyond string expression operators. For instance, given an instance str of the built-in string object type:

str.find(substr)

Performs substring searches

str.replace(old, new)

Performs substring substitutions

str.split(delim)

Chops up a string around delimiters

str.join(seq)

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)

Tests for a substring at the end

str.startswith(substr)

Tests for a substring at the front

This list is representative but partial, and some of these methods take additional optional 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 documentation. The Python library manual also includes an exhaustive list.

Moreover, in Python today, Unicode (wide) strings fully support all normal string methods, and most of the older string module’s functions are also now available as string object methods. For instance, in Python 2.0 and later, the following two expressions are equivalent:

string.find(aString, substr) # original module aString.find(substr) ...

Get Programming Python, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.