String Manipulation

Learn about string manipulation and its implementation using multiple methods.

Overview

Strings can be created in Python by wrapping a sequence of characters in single or double quotes. Multiline strings can easily be created using three quote characters, and multiple hardcoded strings can be concatenated together by placing them side by side. Here are some examples:

Press + to interact
>>> a = "hello"
>>> b = 'world'
>>> c = '''a multiple
... line string'''
>>> d = """More
... multiple"""
>>> e = ("Three " "Strings " "Together")

That last string is automatically composed into a single string by the interpreter. It is also possible to concatenate strings using the + operator (as in "hello " + "world"). Of course, strings don’t have to be hardcoded. They can also come from various outside sources, such as text files and user input, or can be transmitted on the network.

Note: The automatic concatenation of adjacent strings can make for some hilarious bugs when a comma is missed. It is, however, extremely useful when a long string needs to be placed inside a function call without exceeding the 79-character line-length limit suggested by PEP-8, the Python style guide.

Like other sequences, strings can be iterated over (character by character), indexed, sliced, or concatenated. The syntax is the same as for lists and tuples.

The str class has numerous methods on it to make manipulating strings easier. The dir() and help() functions can tell us how to use all of them; we’ll consider some of the more common ...