O'Reilly logo

Programming Python, 3rd Edition by Mark Lutz

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required