Strings and Character Data in Python

Strings and Character Data in Python

by Leodanis Pozo Ramos Updated Reading time estimate 1h 3m basics python

Python strings are a sequence of characters used for handling textual data. You can create strings in Python using quotation marks or the str() function, which converts objects into strings. Strings in Python are immutable, meaning once you define a string, you can’t change it.

By the end of this tutorial, you’ll understand that:

  • The str() function converts objects to their string representation.
  • String interpolation in Python allows you to insert values into {} placeholders in strings using f-strings or the .format() method.
  • You access string elements in Python using indexing with square brackets.
  • You can slice a string in Python by using the syntax string[start:end] to extract a substring.
  • You concatenate strings in Python using the + operator or by using the .join() method.

You’ll explore creating strings with string literals and functions, using operators and built-in functions with strings, indexing and slicing techniques, and methods for string interpolation and formatting. These skills will help you manipulate and format textual data in your Python programs effectively.

To get the most out of this tutorial, you should have a good understanding of core Python concepts, including variables, functions, and operators and expressions.

Take the Quiz: Test your knowledge with our interactive “Python Strings and Character Data” quiz. You’ll receive a score upon completion to help you track your learning progress:


Interactive Quiz

Python Strings and Character Data

This quiz will test your understanding of Python's string data type and your knowledge about manipulating textual data with string objects. You'll cover the basics of creating strings using literals and the str() function, applying string methods, using operators and built-in functions, and more!

Getting to Know Strings and Characters in Python

Python provides the built-in string (str) data type to handle textual data. Other programming languages, such as Java, have a character data type for single characters. Python doesn’t have that. Single characters are strings of length one.

In practice, strings are immutable sequences of characters. This means you can’t change a string once you define it. Any operation that modifies a string will create a new string instead of modifying the original one.

A string is also a sequence, which means that the characters in a string have a consecutive order. This feature allows you to access characters using integer indices that start with 0. You’ll learn more about these concepts in the section about indexing strings. For now, you’ll learn about how to create strings in Python.

Creating Strings in Python

There are different ways to create strings in Python. The most common practice is to use string literals. Because strings are everywhere and have many use cases, you’ll find a few different types of string literals. There are standard literals, raw literals, formatted literals, and, since Python 3.14, template literals.

Additionally, you can use the built-in str() function to create new strings from other existing objects.

In the following sections, you’ll learn about the multiple ways to create strings in Python and when to use each of them.

Standard String Literals

A standard string literal is just a piece of text or a sequence of characters that you enclose in quotes. To create single-line strings, you can use single ('') and double ("") quotes:

Language: Python
>>> 'A single-line string in single quotes'
'A single-line string in single quotes'

>>> "A single-line string in double quotes"
'A single-line string in double quotes'

In the first example, you use single quotes to delimit the string literal. In the second example, you use double quotes.

You can define empty strings using quotes without placing characters between them:

Language: Python
>>> ""
''

>>> ''
''

>>> len("")
0

An empty string doesn’t contain any characters, so when you use the built-in len() function with an empty string as an argument, you get 0 as a result.

To create multiline strings, you can use triple-quoted strings. In this case, you can use either single or double quotes:

Language: Python
>>> '''A triple-quoted string
... spanning across multiple
... lines using single quotes'''
'A triple-quoted string\nspanning across multiple\nlines using single quotes'

>>> """A triple-quoted string
... spanning across multiple
... lines using double quotes"""
'A triple-quoted string\nspanning across multiple\nlines using double quotes'

The primary use case for triple-quoted strings is to create multiline strings. You can also use them to define single-line strings, but this is a less common practice.

Probably the most common use case for triple-quoted strings is when you need to provide docstrings for your packages, modules, functions, classes, and methods.

If you want to include a quote character within the string, then you can delimit that string with another type of quote. For example, if a string contains a single quote character, then you can delimit it with double quotes, and vice versa:

Language: Python
>>> "This string contains a single quote (') character"
"This string contains a single quote (') character"

>>> 'This string contains a double quote (") character'
'This string contains a double quote (") character'

In the first example, your string includes a single quote as part of the text. To delimit the literal, you use double quotes. In the second example, you do the opposite.

Escape Sequences in String Literals

Sometimes, you want Python to interpret a character or sequence of characters within a string differently. This may occur in one of two ways. You may want to:

  1. Apply special meaning to characters
  2. Suppress special character meaning

To achieve these goals, you can use a backslash (\) character combined with other characters. The combination of a backslash and a specific character is called an escape sequence. That’s because the backslash causes the subsequent character to escape its usual meaning.

For example, you can escape a single quote character using the \' escape sequence in a string delimited by single quotes:

Language: Python
>>> 'This string contains a single quote (\') character'
"This string contains a single quote (') character"

In this example, the backslash escapes the single quote character by suppressing its usual meaning, which is delimiting string literals. Now, Python knows that your intention isn’t to terminate the string but to embed the single quote.

The following table shows sequences that escape the default meaning of characters in string literals:

Character Usual Interpretation Escape Sequence Escaped Interpretation
' Delimits a string literal \' Literal single quote (') character
" Delimits a string literal \" Literal double quote (") character
<newline> Terminates the input line \<newline> Newline is ignored
\ Introduces an escape sequence \\ Literal backslash (\) character

You already have an idea of how the first two escape sequences work. Now, how does the newline escape sequence work? Usually, a newline character terminates a physical line of input. To add a newline character, you just press Enter in the middle of a string. This will raise a SyntaxError exception:

Language: Python
>>> "Hello
  File "<input>", line 1
    "Hello
    ^
SyntaxError: unterminated string literal (detected at line 1)

When you press Enter after typing "Hello, you get a SyntaxError. If you need to break up a string over more than one line, then you can include a backslash before each newline or before pressing the Enter key:

Language: Python
>>> "Hello\
... , World\
... !"
'Hello, World!'

When you add a backslash before you press Enter, Python ignores the newline and interprets the whole construct as a single physical line.

Sometimes, you need to include a literal backslash character in a string. If that backslash doesn’t precede a character with a special meaning, then you can insert it right away:

Language: Python
>>> "This string contains a backslash (\) character"
'This string contains a backslash (\\) character'

In this example, the character after the backslash doesn’t match any known escape sequence, so Python inserts the actual backslash for you. Note how the resulting string automatically doubles the backslash. Even though this example works, the best practice is to always double the backslash when you need this character in a string.

However, you may have the need to include a backslash right before a character that makes up an escape sequence:

Language: Python
>>> "In this string, the backslash should be at the end \"
  File "<input>", line 1
    "In this string, the backslash should be at the end \"
    ^
SyntaxError: unterminated string literal (detected at line 1); perhaps you escaped the end quote?

Because the sequence \" matches a known escape sequence, your string fails with a SyntaxError. To avoid this issue, you can double the backslash:

Language: Python
>>> "In this string, the backslash should be at the end \\"
'In this string, the backslash should be at the end \\'

In this update, you double the backslash to escape the character and prevent Python from raising an error.

Up to this point, you’ve learned how to suppress the meaning of a given character by escaping it. Suppose you need to create a string containing a tab character. Some text editors may allow you to insert a tab character directly into your code. However, this is considered a poor practice for several reasons:

  • Computers can distinguish between tabs and a sequence of spaces, but human beings can’t because these characters are visually indistinguishable.
  • Some text editors automatically eliminate tabs by expanding them to an appropriate number of spaces.
  • Some Python REPL environments won’t insert tabs into code.

In Python, you can specify a tab character with the \t escape sequence:

Language: Python
>>> print("Before\tAfter")
Before    After

The \t escape sequence changes the usual meaning of the letter t, making Python interpret the combination as a tab character.

Here’s a list of escape sequences that cause Python to apply special meaning to some characters instead of interpreting them literally:

Escape Sequence Escaped Interpretation
\a ASCII Bell (BEL) character
\b ASCII Backspace (BS) character
\f ASCII Formfeed (FF) character
\n ASCII Linefeed (LF) character
\N{<name>} Character from Unicode database with given <name>
\r ASCII Carriage return (CR) character
\t ASCII Horizontal tab (TAB) character
\uxxxx Unicode character with 16-bit hex value xxxx
\Uxxxxxxxx Unicode character with 32-bit hex value xxxxxxxx
\v ASCII Vertical tab (VT) character
\ooo Character with octal value ooo
\xhh Character with hex value hh

The newline or linefeed character (\n) is probably the most popular of these escape sequences. This sequence is commonly used to create nicely formatted text outputs that span multiple lines.

Here are a few examples of the escape sequences in action:

Language: Python
>>> # Tab
>>> print("a\tb")
a    b

>>> # Linefeed
>>> print("a\nb")
a
b

>>> # Octal
>>> print("\141")
a

>>> # Hex
>>> print("\x61")
a

>>> # Unicode by name
>>> print("\N{rightwards arrow}")
→

These escape sequences are useful when you need to insert characters that aren’t readily generated from the keyboard or aren’t easily readable or printable.

Raw String Literals

With raw string literals, you can create strings that don’t translate escape sequences. Any backslash characters are left in the string.

To create a raw string, you have to prepend the string literal with the letter r or R:

Language: Python
>>> print("Before\tAfter")  # Regular string
Before    After

>>> print(r"Before\tAfter")  # Raw string
Before\tAfter

The raw string suppresses the meaning of the escape sequence, such as \t, and presents the characters as they are.

Raw strings are commonly used to create regular expressions because they allow you to use several different characters that may have special meanings without restrictions.

For example, say that you want to create a regular expression to match email addresses. To do this, you can use a raw string to create the regular expression like in the code below:

Language: Python
>>> import re

>>> pattern = r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b"
>>> pattern
'\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Z|a-z]{2,}\\b'

>>> regex = re.compile(pattern)

>>> text = """
...     Please contact us at support@example.com
...     or sales@example.com for further information.
... """

>>> regex.findall(text)
['support@example.com', 'sales@example.com']

The pattern variable holds a raw string that makes up a regular expression to match email addresses. Note how the string contains several backslashes that are escaped and inserted into the resulting string as they are. Then, you compile the regular expression and check for matches in a sample piece of text.

Formatted String Literals

Formatted string literals, or f-strings for short, allow you to interpolate values into your strings and format them as you need.

To create a string with an f-string literal, you must prepend the literal with an f or F letter. F-strings let you interpolate values into replacement fields in your string literal. You create these fields using curly brackets.

Here’s a quick example of an f-string literal:

Language: Python
>>> name = "Jane"

>>> f"Hello, {name}!"
'Hello, Jane!'

In this example, you interpolate the name variable into your string using an f-string literal and a replacement field.

You’ll learn more about using f-strings for string interpolation and formatting in the Doing String Interpolation and Formatting section.

The Built-in str() Function

You can create new strings using the built-in str() function. However, a more common use case for this function is to convert other data types into strings, which is also a way to create new strings.

Consider the following examples:

Language: Python
>>> str()
''

>>> str(42)
'42'

>>> str(3.14)
'3.14'

>>> str([1, 2, 3])
'[1, 2, 3]'

>>> str({"one": 1, "two": 2, "three": 3})
"{'one': 1, 'two': 2, 'three': 3}"

>>> str({"A", "B", "C"})
"{'B', 'C', 'A'}"

In the first example, you call the str() function without an argument to create an empty string. Then, you use the function to convert objects from different built-in types into strings.

Using Operators on Strings

You can also use a few operators with string values as operands. For example, the + and * operators allow you to perform string concatenation and repetition, respectively. In the following sections, you’ll learn how these and other operators work with strings.

Concatenating Strings: The + Operator

The + operator lets you concatenate strings. So, in this context, you can call it the concatenation operator. Concatenation involves joining two or more string objects to create a single new string:

Language: Python