Strings
Learn how Python stores and manipulates text with strings, including quoting styles, immutability, indexing, slicing, concatenation, and escape sequences.
Introduction
Almost every program deals with text in some form — names, messages, file paths, sentences, or entire documents. In Python, text is represented using a data type called a string. You already used strings briefly in earlier lessons, but now it is time to understand exactly how they work under the hood.
In this lesson you will learn how to create strings, why they cannot be changed once created, and how to pick out individual characters or entire chunks of text using indexing and slicing.
- How to create strings using single, double, and triple quotes.
- Why strings are immutable in Python.
- How to access characters using indexing and slicing.
- How to combine and repeat strings.
- How to use escape sequences and write multi-line text.
- How to check whether text exists inside a string using in.
What is a String?
A string is a sequence of characters — letters, numbers, symbols, or spaces — wrapped in quotes. In Python, the type name for a string is str.
message = "Hello, Python!"
print(message)
print(type(message))Hello, Python!
<class 'str'>Because a string is a sequence, Python lets you loop over it, measure its length, and access individual characters by position — just like you would with a list of items.
Creating Strings
Python gives you three ways to wrap text: single quotes, double quotes, and triple quotes. All three create the same str type — the choice mostly comes down to convenience and style.
Single Quotes 'text'
The most common style for short strings. Great when the text itself contains double quotes.
Double Quotes "text"
Functionally identical to single quotes. Useful when the text contains an apostrophe.
Triple Quotes ''' or """
Used for strings that span multiple lines, or for docstrings that document code.
single = 'Learning Python'
double = "Learning Python"
contains_apostrophe = "It's a sunny day"
contains_quotes = 'She said "hello"'
print(single)
print(double)
print(contains_apostrophe)
print(contains_quotes)Learning Python
Learning Python
It's a sunny day
She said "hello"- Pick one style (single or double) and stay consistent within a project.
- Use the other quote type when your text contains an apostrophe or quotation marks.
- Use triple quotes for text that spans several lines.
Strings Are Immutable
Once a string is created, it cannot be changed in place. This property is called immutability. If you try to modify a single character of a string directly, Python raises an error.
word = "cat"
word[0] = "b"Traceback (most recent call last):
...
TypeError: 'str' object does not support item assignmentInstead of modifying a string, you create a brand-new string with the changes you want. The original string is left untouched.
word = "cat"
word = "b" + word[1:]
print(word)bat- It makes strings safe to share between different parts of a program without unexpected changes.
- It allows Python to optimize memory by reusing identical strings internally.
- It is a concept you will meet again with tuples in a later lesson.
Indexing
Every character in a string has a position, called an index. Python indexing starts at 0, not 1, so the first character is at index 0, the second at index 1, and so on.
name = "Python"
print(name[0])
print(name[1])
print(name[5])P
y
nPython also supports negative indexing, which counts backward from the end of the string. The last character is at index -1, the second-to-last at -2, and so on. This is handy when you do not know (or do not want to calculate) the exact length of a string.
name = "Python"
print(name[-1])
print(name[-2])n
oAccessing an index that does not exist raises an IndexError. For a 6-character string, valid positive indices are 0 through 5 — index 6 does not exist.
Slicing
While indexing grabs a single character, slicing grabs a whole chunk of a string using the syntax string[start:stop:step]. The start index is included, and the stop index is excluded.
word = "Programming"
print(word[0:6])
print(word[:4])
print(word[4:])
print(word[:])Progra
Prog
ramming
ProgrammingYou can also slice with negative indices, and you can add a step value to skip characters — for example, a step of 2 takes every second character, and a step of -1 reverses the string.
word = "Programming"
print(word[-3:])
print(word[::2])
print(word[::-1])ing
Pormig
gnimmargorP| Slice | Meaning |
|---|---|
| s[a:b] | Characters from index a up to (not including) b |
| s[:b] | Everything from the start up to index b |
| s[a:] | Everything from index a to the end |
| s[::step] | Every step-th character across the whole string |
| s[::-1] | The entire string, reversed |
Concatenation and Repetition
You can join strings together using the + operator, called concatenation. You can also repeat a string multiple times using the * operator.
first = "Hello"
second = "World"
full = first + second
spaced = first + " " + second
print(full)
print(spaced)HelloWorld
Hello Worldborder = "-" * 20
print(border)
print("ha" * 3)--------------------
haha haThe + operator only works between two strings. Trying "Score: " + 90 raises a TypeError because you cannot concatenate a string and an integer directly — convert the number with str(90) first.
Escape Sequences
Sometimes you need to include characters in a string that would otherwise confuse Python, like a quote mark inside a quoted string, or a special character like a newline or tab. Escape sequences use a backslash to represent these characters.
| Escape Sequence | Meaning |
|---|---|
| \n | Newline (moves to the next line) |
| \t | Tab (horizontal space) |
| \' | A literal single quote |
| \" | A literal double quote |
| \\ | A literal backslash |
print("Line one\nLine two")
print("Name:\tAlex")
print('It\'s a great day')
print("File path: C:\\Users\\Alex")Line one
Line two
Name: Alex
It's a great day
File path: C:\Users\AlexMulti-line Strings
Triple-quoted strings let you write text that spans several lines without needing \n escape sequences. Every line break you type becomes part of the string.
message = """Dear Student,
Welcome to the Python course.
We are glad you are here.
"""
print(message)Dear Student,
Welcome to the Python course.
We are glad you are here.Checking Membership with in
The in keyword lets you check whether one string appears inside another, returning True or False. This is often used inside if statements, which you will study soon.
sentence = "Python is fun to learn"
print("fun" in sentence)
print("Java" in sentence)
print("Java" not in sentence)True
False
TrueA Sneak Peek at String Methods
Beyond indexing and slicing, strings come with a large collection of built-in methods for tasks like converting case, removing extra spaces, splitting text apart, and searching for substrings. You have already seen a hint of this with functions like len(). The next lesson, String Methods, is dedicated entirely to exploring these tools in depth, so we will not cover them here.
text = "hello python"
print(len(text))12Common Mistakes
- Forgetting that indexing starts at 0, not 1.
- Trying to change a string in place, like word[0] = "b", instead of building a new string.
- Mixing up slice bounds — remember the stop index is excluded.
- Concatenating a string with a number without converting the number using str() first.
- Forgetting to close a quote, or mismatching single and double quotes.
Best Practices
- Be consistent about using single or double quotes throughout a project.
- Use triple quotes for genuinely multi-line text, not as a shortcut for regular strings.
- Prefer slicing over manual loops when extracting parts of a string.
- Use in for simple substring checks instead of more complex methods.
- Remember that any "modified" string is actually a brand-new string object.
Frequently Asked Questions
What is the difference between single and double quotes in Python?
There is no functional difference — both create a str. Choose whichever avoids extra escaping for the text you are writing.
Can I change a single character in a string?
Not directly. Strings are immutable, so you must build a new string that includes the change, for example using slicing and concatenation.
What happens if I slice past the end of a string?
Python will not raise an error — it simply stops at the end of the string. For example, "hi"[0:100] safely returns "hi".
How do I reverse a string?
Use extended slicing with a step of -1, like my_string[::-1].
Why did I not learn upper() or split() in this lesson?
Those are string methods, which get a full lesson of their own right after this one so you can focus on them in depth.
Key Takeaways
- Strings represent text and can be created with single, double, or triple quotes.
- Strings are immutable — any change creates a new string.
- Indexing accesses a single character; slicing extracts a range using start:stop:step.
- Negative indices count backward from the end of the string.
- The + operator concatenates strings and * repeats them.
- Escape sequences like \n and \t represent special characters.
- The in keyword checks whether a substring exists inside a string.
Summary
Strings are one of the most frequently used data types in Python. You now know how to create them, why they cannot be modified in place, and how to extract exactly the piece of text you need using indexing and slicing.
In the next lesson, you will build on this foundation by exploring the many built-in methods Python provides for working with strings.
- You can create strings with different quoting styles.
- You understand why strings are immutable.
- You can index and slice strings confidently, including with negative numbers and steps.
- You are ready to explore string methods in depth.