Python Strings
Strings
A string in Python is a sequence of characters used to represent text. Names, email addresses, messages, file paths, and web page content are all stored as strings. The string data type in Python is called str.
This lesson covers how to create strings, access individual characters, slice parts of a string, modify strings with built-in methods, join strings together, format strings with f-strings, and use escape characters.
Creating Strings
Strings can be written with either single quotes (' ') or double quotes (" "). Both work exactly the same way.
Displaying a String
print("Welcome to Python")
print('Learning strings is easy')
Expected output:
Welcome to Python
Learning strings is easy
Using Quotes Inside a String
You can include quotation marks inside a string as long as they are different from the quotes used to define the string.
print("Python is called 'easy to learn'")
print('She said, "Practice daily"')
print("It's a great day to code")
Expected output:
Python is called 'easy to learn'
She said, "Practice daily"
It's a great day to code
Python decides where a string ends by looking for the matching closing quote. Because the inner quotes are a different type, Python treats them as ordinary characters.
Assigning a String to a Variable
Strings are commonly stored in variables so they can be reused later in a program.
greeting = "Hello, Developer!"
print(greeting)
Expected output:
Hello, Developer!
Multi-Line Strings
To store text across multiple lines, use triple quotes — either """ """ or ''' '''. Line breaks in the code are preserved in the string.
Example: Triple Double Quotes
message = """Python is powerful,
easy to read,
and widely used."""
print(message)
Expected output:
Python is powerful,
easy to read,
and widely used.
Example: Triple Single Quotes
note = '''This is a multi-line string.
It is useful for long messages
or documentation.'''
print(note)
Expected output:
This is a multi-line string.
It is useful for long messages
or documentation.
Multi-line strings are useful for long messages, email templates, SQL queries, and documentation strings (docstrings).
Strings Are Sequences of Characters
In Python, a string is an ordered sequence of Unicode characters. Each character has a numbered position called an index, and indexing starts at 0.
For the string "Python":
| Character | P | y | t | h | o | n |
|---|---|---|---|---|---|---|
| Positive index | 0 | 1 | 2 | 3 | 4 | 5 |
| Negative index | -6 | -5 | -4 | -3 | -2 | -1 |
Accessing a Character by Index
Use square brackets [ ] with the index number:
text = "Python"
print(text[2])
print(text[0])
print(text[-1])
Expected output:
t
P
n
text[2]returns the character at index 2, which is the third character,t.text[0]returns the first character.text[-1]returns the last character. Negative indexes count from the end.
Using an index that does not exist raises an error:
text = "Python"
print(text[10])
Output:
IndexError: string index out of range
Note: Python has no separate "character" type. A single character is simply a string of length 1.
Strings Are Immutable
Strings cannot be changed after they are created. You cannot replace a character by assigning to an index:
text = "Python"
text[0] = "J"
Output:
TypeError: 'str' object does not support item assignment
Instead, create a new string:
text = "Python"
new_text = "J" + text[1:]
print(new_text)
Expected output:
Jython
This is why all string methods (covered later in this lesson) return a new string rather than modifying the original.
Looping Through a String
Because strings are sequences, they are iterable — you can loop through each character with a for loop.
for letter in "coding":
print(letter)
Expected output:
c
o
d
i
n
g
On each pass through the loop, letter holds the next character in the string.
Practical Example: Counting Vowels
word = "education"
vowel_count = 0
for letter in word:
if letter in "aeiou":
vowel_count += 1
print("Vowels:", vowel_count)
Expected output:
Vowels: 5
Finding the Length of a String
Use the built-in len() function to find how many characters a string contains. Spaces and punctuation are counted too.
title = "Python Strings"
print(len(title))
Expected output:
14
"Python Strings" has 6 letters, 1 space, and 7 more letters: 14 characters in total.
Because indexing starts at 0, the last valid index of a string is always len(string) - 1.
Checking for Text Inside a String
Using in
The in keyword checks whether a word or character exists in a string. It returns True or False.
sentence = "Practice makes progress"
print("makes" in sentence)
Expected output:
True
The check is case-sensitive: "Makes" in sentence would return False.
Using in With an if Statement
sentence = "Practice makes progress"
if "progress" in sentence:
print("The word 'progress' was found.")
Expected output:
The word 'progress' was found.
Checking That Text Is NOT Present
Use not in to confirm that a word or character does not exist in a string.
sentence = "Practice makes progress"
print("failure" not in sentence)
Expected output:
True
Using not in With an if Statement
sentence = "Practice makes progress"
if "failure" not in sentence:
print("The word 'failure' is not present.")
Expected output:
The word 'failure' is not present.
String Slicing
Slicing extracts a portion of a string — a substring — by selecting a range of indexes.
Slice Syntax
string[start:end]
startis inclusive — the slice begins at this index.endis exclusive — the slice stops before this index.- Indexing always begins at
0.
A helpful way to remember: the number of characters returned is end - start.
Basic Slicing
text = "Programming"
print(text[3:7])
Expected output:
gram
| Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|
| Character | P | r | o | g | r | a | m | m | i | n | g |
The slice starts at index 3 (g) and stops before index 7, returning indexes 3, 4, 5, and 6: gram.
Slicing From the Beginning
If you omit the start index, slicing begins at the first character.
word = "Developer"
print(word[:4])
Expected output:
Deve
This returns indexes 0 to 3 — the first four characters.
Slicing Until the End
If you omit the end index, slicing continues to the last character.
language = "Pythonista"
print(language[6:])
Expected output:
ista
This extracts everything from index 6 to the end of the string.
Slicing With Negative Indexes
Negative indexes count from the end of the string:
-1refers to the last character-2refers to the second-last character, and so on
text = "SlicingExample"
print(text[-7:-3])
Expected output:
Exam
The slice starts at the 7th character from the end (E) and stops before the 3rd character from the end (p), returning Exam.
Slicing With a Step
An optional third value, the step, controls how many characters to move each time:
string[start:end:step]
text = "Python"
print(text[0:6:2])
print(text[::-1])
Expected output:
Pto
nohtyP
text[0:6:2]takes every second character.text[::-1]uses a step of-1to read the string backwards — a common way to reverse a string.
Note: Unlike indexing, slicing never raises an
IndexError. If the indexes are out of range, Python simply returns as many characters as are available.
Modifying Strings
Python provides many built-in methods for working with strings. A method is a function that belongs to a value and is called with a dot: text.upper().
Because strings are immutable, these methods do not change the original string — they return a new string.
Converting to Uppercase
upper() converts all characters to uppercase.
title = "python programming"
print(title.upper())
Expected output:
PYTHON PROGRAMMING
Converting to Lowercase
lower() converts all characters to lowercase.
email = "User@Example.COM"
print(email.lower())
Expected output:
user@example.com
Converting to lowercase is useful for case-insensitive comparisons, such as checking email addresses.
Removing Extra Spaces
strip() removes whitespace from the beginning and end of a string. Spaces between words are kept.
name = " Alice Johnson "
print(name.strip())
Expected output:
Alice Johnson
This is especially useful when cleaning user input, where accidental spaces are common.
Replacing Part of a String
replace() substitutes one substring with another.
message = "I love Java"
print(message.replace("Java", "Python"))
Expected output:
I love Python
By default, replace() replaces every occurrence of the substring.
Splitting a String Into a List
split() divides a string into a list of substrings, using a specified separator.
data = "red|green|blue"
print(data.split("|"))
Expected output:
['red', 'green', 'blue']
If you call split() without a separator, it splits on any whitespace. This method is useful when processing CSV data, user input, or file content.
Methods Return New Strings
This example demonstrates that the original string is unchanged:
city = "chennai"
city.upper()
print(city)
city = city.upper()
print(city)
Expected output:
chennai
CHENNAI
The first call to upper() creates a new string but does not store it, so city is unchanged. To keep the result, assign it back to a variable.
Concatenating Strings
String concatenation means joining two or more strings into a single string. This is commonly done with the + operator.
Joining Two Strings
first_name = "Suriya"
last_name = "R"
full_name = first_name + last_name
print(full_name)
Expected output:
SuriyaR
The + operator joins strings exactly as they are — it does not add spaces.
Adding a Space Between Strings
To separate words, add a space string manually:
city = "New"
name = "Delhi"
location = city + " " + name
print(location)
Expected output:
New Delhi
Concatenating Multiple Strings
course = "Python"
level = "Beginner"
platform = "Online"
details = course + " " + level + " " + platform
print(details)
Expected output:
Python Beginner Online
Important Notes on Concatenation
- Only strings can be concatenated with
+. - Numbers must be converted with
str()before concatenation. - For combining text with values, f-strings are usually clearer (see the next section).
- To join many strings from a list, the
join()method is more efficient:" ".join(["Python", "Beginner", "Online"]).
String Formatting
Strings and numbers cannot be joined directly with +. Attempting to do so raises a TypeError, because Python treats text and numbers as different data types.
Incorrect Example
year = 2026
message = "Current year is " + year
print(message)
Output:
TypeError: can only concatenate str (not "int") to str
To combine text with numbers safely, Python provides string formatting techniques such as f-strings and the format() method.
Using F-Strings (Recommended)
F-strings (formatted string literals) were introduced in Python 3.6. They are the most readable and commonly recommended way to format strings.
To create an f-string:
- Put the letter
fbefore the opening quote. - Place variables or expressions inside curly braces
{}.
username = "Alex"
points = 120
output = f"User {username} has scored {points} points"
print(output)
Expected output:
User Alex has scored 120 points
Python replaces {username} and {points} with their values and converts them to text automatically — no str() is required.
Placeholders in F-Strings
The {} sections are called placeholders. They can contain:
- Variables
- Mathematical expressions
- Function and method calls
- Formatting rules
Using Variables Inside Placeholders
product = "Laptop"
cost = 45000
info = f"The cost of the {product} is {cost} rupees"
print(info)
Expected output:
The cost of the Laptop is 45000 rupees
Using Expressions Inside Placeholders
F-strings can evaluate Python expressions directly.
items = 5
price_per_item = 199
bill = f"Total amount to pay: {items * price_per_item} rupees"
print(bill)
Expected output:
Total amount to pay: 995 rupees
Formatting Values With Modifiers
You can control how a value is displayed with a format specifier, written after a colon : inside the placeholder.
temperature = 36.67891
result = f"Today's temperature is {temperature:.1f}°C"
print(result)
Expected output:
Today's temperature is 36.7°C
.1f means "display as a fixed-point number with 1 decimal place". The value is rounded for display; the variable itself is unchanged.
More useful format specifiers:
| Specifier | Example | Result | Meaning |
|---|---|---|---|
.2f | f"{3.14159:.2f}" | 3.14 | 2 decimal places |
, | f"{45000:,}" | 45,000 | Thousands separator |
.1% | f"{0.875:.1%}" | 87.5% | Percentage with 1 decimal place |
03d | f"{7:03d}" | 007 | Pad an integer with zeros to width 3 |
Why F-Strings Are Preferred
- Cleaner and more readable syntax — the values appear exactly where they will be in the output
- Automatic conversion of numbers and other values to text
- Support for inline calculations and formatting
- Generally faster than older formatting methods
String formatting is covered in more depth in the Python Formatting Strings lesson.
Escape Characters
Escape characters are special sequences used inside strings to represent characters that cannot be typed directly, or that would otherwise break the string syntax.
An escape sequence always begins with a backslash (``), followed by a character that has a predefined meaning.
Why Escape Characters Are Needed
Some characters — such as quotes, new lines, and tabs — have special meanings. Using them directly inside a string can cause a syntax error or be interpreted incorrectly.
Problem Example
text = "This is my "Python" program"
This raises a SyntaxError. Python thinks the string ends at the second ", just before Python, and the rest of the line becomes invalid code.
Correct Example
Prefix the inner quotes with a backslash:
text = "This is my \"Python\" program"
print(text)
Expected output:
This is my "Python" program
\" tells Python: "this is a literal quote character, not the end of the string."
Commonly Used Escape Characters
| Escape Sequence | Meaning |
|---|---|
\' | Single quote |
\" | Double quote |
0 | Backslash |
\n | New line |
\t | Tab |
\r | Carriage return |
\b | Backspace |
\f | Form feed |
\ooo | Character with the given octal value |
\xhh | Character with the given hexadecimal value |
Single Quote (\')
msg = 'It\'s a sunny day'
print(msg)
Expected output:
It's a sunny day
Backslash (0)
A single backslash starts an escape sequence, so to display one backslash you must write two.
path = "C:\\Users\\Admin\\Documents"
print(path)
Expected output:
C:\Users\Admin\Documents
New Line (\n)
note = "Line one\nLine two\nLine three"
print(note)
Expected output:
Line one
Line two
Line three
Tab (\t)
data = "Name\tAge\tCity"
print(data)
Expected output (tab widths may vary in your terminal):
Name Age City
Tabs are useful for simple column alignment in console output.
Carriage Return (\r)
text = "Hello\rWorld"
print(text)
\r moves the cursor back to the beginning of the current line, so the text after it overwrites the text before it. In most terminals, the output is:
World
Note: How
\r,\b, and\fare displayed depends on the terminal or editor. Some IDE consoles show them differently, so do not rely on them for important formatting.
Backspace (\b)
\b moves the cursor back one position, so the next character overwrites the previous one.
word = "Pythx\bon"
print(word)
In most terminals, the output is:
Python
The x is printed, \b moves the cursor back over it, and o replaces it.
Form Feed (\f)
text = "Page1\fPage2"
print(text)
The form feed character was originally used to tell printers to start a new page. In modern terminals, it is usually displayed as a line break or a special symbol, and it is rarely used today.
Numeric Escape Sequences
You can represent a character by its numeric code.
Octal Value (\ooo)
char = "\101"
print(char)
Expected output:
A
101 in octal (base 8) equals 65 in decimal, which is the character code for A.
Hexadecimal Value (\xhh)
symbol = "\x41"
print(symbol)
Expected output:
A
41 in hexadecimal (base 16) also equals 65, so this produces A as well.
Raw Strings
If a string contains many backslashes — such as a Windows file path or a regular expression — you can prefix it with r to create a raw string. In a raw string, backslashes are treated as ordinary characters.
path = r"C:\new\table"
print(path)
Expected output:
C:\new\table
Without the r prefix, \n and \t would be interpreted as a new line and a tab.
Common Mistakes
| Mistake | Example | Result |
|---|---|---|
| Changing a character by index | text[0] = "J" | TypeError — strings are immutable |
| Expecting a method to change the original | name.upper() without assignment | The original string is unchanged |
Joining a string and a number with + | "Age: " + 25 | TypeError |
| Off-by-one slicing | Expecting text[0:3] to include index 3 | The end index is excluded |
| Unescaped backslashes in Windows paths | "C:\new" | \n becomes a new line |
| Matching quotes inside a string | "He said "hi"" | SyntaxError |
Related Concepts
- Python String Methods — a complete reference of built-in string methods
- Python Formatting Strings — f-strings and
format()in depth - Python Lists — sequences that, unlike strings, can be modified
- Python RegEx — searching and matching text patterns