Python Strings

Strings in Python are ordered sequences of characters used to store and work with text.

What is a String?

A string is any run of text wrapped in quotes. Python treats a single character and a long paragraph the same way: both are values of the built-in str type. You can create a string with single quotes, double quotes, or triple quotes, and Python does not care which you pick as long as the opening and closing marks match.

Creating strings

greeting = 'Hello'
name = "Ada"
quote = 'She said "hi" to me'

print(greeting)
print(name)
print(quote)

Mixing quote styles is handy when the text itself contains a quote character, as shown above with the double quotes living inside a single-quoted string. This avoids having to escape the inner quotes.

Multiline Strings

When you need a string that spans several lines, wrap it in three quote marks. The line breaks you type inside the triple quotes are preserved in the final value, which makes this style useful for longer blocks of text.

Triple-quoted text

message = """Dear reader,
Thanks for learning Python.
See you soon."""

print(message)
Note: Strings are immutable in Python. Once created, a string's characters cannot be changed in place. Any operation that looks like it edits a string actually builds and returns a brand-new string.

Common String Operations

  • Find the length of a string with len(text).
  • Join two strings together using the + operator (concatenation).
  • Repeat a string with the * operator, for example '-' * 10.
  • Check whether a substring is present using the in keyword.
  • Loop over a string to visit one character at a time.

Working with strings

word = "Python"

print(len(word))
print(word + " rocks")
print("ab" * 3)
print("y" in word)

for letter in word:
    print(letter)

Exercise: Python Strings

What happens when you try to change one character of a string with s[0] = 'H'?