Table of Contents
Why Text Matters in Programs
In many programs, you don’t only work with numbers—you also work with words, sentences, names, messages, and other text. In Python, pieces of text are stored in a data type called a string, written as str (short for “string”).
A string can hold anything you can type on a keyboard: letters, digits, spaces, punctuation, and even symbols.
Creating Strings
You create a string by putting text inside quotes. You can use either single quotes ' or double quotes ".
message = "Hello, world!"
name = 'Alice'
address = "221B Baker Street"
number_as_text = "12345" # This is text, NOT a numberPython doesn’t care whether you use single or double quotes, but they must match: open and close with the same type.
This is valid:
greeting = "Hello"
reply = 'Hi'This is not valid (unmatched quotes):
# This will cause a SyntaxError
wrong = "Hello'Empty Strings
You can also create an “empty” string with nothing inside the quotes:
empty1 = ""
empty2 = ''An empty string is still a string; it just has length $0$ (no characters).
Strings Are Sequences of Characters
A string is a sequence (ordered collection) of characters. Each character has a position (index), starting from $0$.
For the string:
word = "Python"The characters and their positions are:
P→ index $0$y→ index $1$t→ index $2$h→ index $3$o→ index $4$n→ index $5$
Python lets you access individual characters using square brackets []:
word = "Python"
first_letter = word[0]
third_letter = word[2]
print(first_letter) # P
print(third_letter) # tTrying to use an index that is too large will cause an error, because there is no character at that position.
Basic String Operations
You’ll see some of these operations again in more detail later, but here are the most common things you can do with str.
String Concatenation (Joining Text)
You can join strings together using the + operator. This is called concatenation.
first_name = "Ada"
last_name = "Lovelace"
full_name = first_name + " " + last_name
print(full_name) # Ada Lovelace
Important: + for strings only works between strings. You can’t directly + a string and a number.
This will cause an error:
age = 30
text = "I am " + age # TypeErrorYou’ll see later how to combine text and numbers safely in another chapter.
Repeating Strings
You can repeat a string using * and an integer.
laugh = "ha"
print(laugh * 3) # hahaha
line = "-" * 40
print(line) # ----------------------------------------
The number must be an integer (int). You cannot multiply by a string or a float.
Special Characters and Escape Sequences
Sometimes you need characters that are hard to type directly inside a string, like a newline (go to the next line) or an actual quote character inside quotes.
Python uses escape sequences, which start with a backslash \.
Common escape sequences:
- Newline:
\n - Tab:
\t - Single quote inside single quotes:
\' - Double quote inside double quotes:
\" - Backslash itself:
\\
text = "First line\nSecond line"
print(text)
# Output:
# First line
# Second line
path = "C:\\Users\\Alice"
print(path) # C:\Users\AliceQuotes Inside Strings
If you want quotes inside a string, you have two main options.
- Use different quotes outside and inside:
sentence1 = "It's a sunny day"
sentence2 = 'He said, "Hello!"'- Escape the quotes:
sentence3 = 'It\'s a sunny day'
sentence4 = "He said, \"Hello!\""Both approaches are common; choose whichever is clearer.
Multiline Strings
If you want a string that spans several lines, you can use triple quotes: """ or '''.
text = """This is a
multiline string.
It has three lines."""
print(text)Python keeps the line breaks as part of the string.
Multiline strings are also often used for long messages or documentation.
Checking the Type of a String
To confirm that a value is a string, you can use type():
message = "Hello"
print(type(message)) # <class 'str'>
print(type("123")) # <class 'str'>
Even if a string looks like a number, it is still of type str if it’s inside quotes.
Length of a String
You can find out how many characters are in a string using len():
word = "Python"
print(len(word)) # 6
empty = ""
print(len(empty)) # 0
phrase = "Hello, world!"
print(len(phrase)) # 13Spaces and punctuation are counted as characters too.
Basic String Methods
Strings come with built-in methods (actions you can perform on them). You call a method with a dot . after the string.
Some useful beginner-friendly methods:
Changing Case: `lower()` and `upper()`
lower()→ returns a version of the string with all letters in lowercaseupper()→ returns a version with all letters in uppercase
name = "Alice"
print(name.lower()) # alice
print(name.upper()) # ALICENote: These methods create new strings; they do not change the original:
name = "Alice"
lower_name = name.lower()
print(name) # Alice
print(lower_name) # aliceRemoving Extra Spaces: `strip()`
strip() removes spaces (and some other whitespace) from the beginning and end of a string.
raw = " hello "
cleaned = raw.strip()
print(raw) # ' hello '
print(cleaned) # 'hello'
There are also lstrip() (left only) and rstrip() (right only).
Finding Substrings: `in`
You can check if one string is contained inside another using the keyword in, which returns a Boolean value (True or False):
sentence = "Python is fun"
print("Python" in sentence) # True
print("Java" in sentence) # FalseConverting Between Strings and Other Types (Overview)
Strings are often used to store user input, which arrives as text. Sometimes you need to convert between strings and numbers.
A quick overview (there is a full chapter later on conversions):
- Convert number → string:
str() - Convert string with digits → integer:
int() - Convert string with digits and a decimal point → float:
float()
age = 30
age_text = str(age) # "30"
number_text = "42"
number_value = int(number_text) # 42
If the text does not look like a number, int() or float() will cause an error.
Common Beginner Mistakes with Strings
1. Forgetting Quotes
Without quotes, Python thinks something is a variable name, not text.
# This will cause a NameError
message = HelloCorrect:
message = "Hello"2. Mixing Numbers and Strings with `+` Directly
age = 25
# This will cause a TypeError
text = "I am " + ageYou need to convert the number or use another method (covered later):
text = "I am " + str(age)3. Using the Wrong Quotes
# SyntaxError: EOL while scanning string literal
text = "She said, "Hi!""Fix by changing outer quotes or escaping inner quotes:
text = 'She said, "Hi!"'
# or
text = "She said, \"Hi!\""Simple Practice Ideas
Here are a few small things you can try to get comfortable with str:
- Store your full name in a variable and print:
- Your name in all lowercase
- Your name in all uppercase
- The length of your name using
len() - Create a string with a sentence, then:
- Check whether your first name appears in the sentence using
in. - Print the sentence on two lines using
\n. - Make a small “divider” line using
*:
line = "=" * 30
print(line)
This chapter’s goal is for you to be comfortable creating and using text values (str) in Python—storing them in variables, joining them, and doing simple operations with them.