Python Strings
Learn how Python stores and works with text. You'll discover how to create strings, combine them, measure them, search them, work with special characters, and understand why strings are immutable.
What You'll Learn
- Understand what strings are and how Python represents text.
- Create strings using different quotation styles.
- Work with multiline strings.
- Measure, combine, repeat, and search strings.
- Understand escape characters and raw strings.
- Understand string immutability.
- Avoid common string-related programming mistakes.
What Are Strings?
A string is a sequence of characters used to represent text in a Python program.
A string can contain letters, numbers, spaces, punctuation marks, and special characters.
"Hello"
"Python"
"12345"
"Python is powerful!"
"student@example.com"
Even when a string contains only numbers, Python treats it as text if it is enclosed in quotation marks.
age = "25"
print(type(age))
<class 'str'>
Important
"25" is a string, while
25 is an integer.
Creating Strings
The simplest way to create a string is to place text inside quotation marks.
name = "Ali"
city = "Multan"
message = "Welcome to PyLearn!"
print(name)
print(city)
print(message)
Ali
Multan
Welcome to PyLearn!
Strings can be assigned to variables just like numbers, lists, and other Python objects.
Single & Double Quotes
Python allows strings to be created using either single quotes or double quotes.
name1 = 'Ali'
name2 = "Sara"
print(name1)
print(name2)
Both approaches create strings.
Choosing the Right Quote
Sometimes one quotation style makes your code easier to read.
message = "It's a beautiful day"
quote = 'He said "Python is easy!"'
Professional Practice
Pick a consistent quotation style for your project and follow it throughout your code.
Multiline Strings
Python supports multiline strings using triple quotes.
message = """Welcome to PyLearn.
Learn Python.
Build projects.
Become confident."""
print(message)
Welcome to PyLearn.
Learn Python.
Build projects.
Become confident.
Triple single quotes can also be used:
text = '''This is
a multiline
string.'''
Strings as Sequences of Characters
A string is not just a single piece of text. It is a sequence of individual characters.
word = "Python"
# Characters:
# P y t h o n
Each character occupies a position within the string. These positions become especially important when we learn string indexing and slicing.
Coming Next
In the next lesson, we'll explore string indexing and slicing in depth.
Finding String Length
Python provides the len() function to
determine how many characters are contained in a string.
word = "Python"
print(len(word))
6
Spaces are also characters.
text = "Hello World"
print(len(text))
11
The space between Hello and
World counts as one character.
String Concatenation
Concatenation means joining strings together.
Python uses the + operator for this.
first_name = "Muhammad"
last_name = "Ali"
full_name = first_name + " " + last_name
print(full_name)
Muhammad Ali
age = 25
# This causes an error:
# print("Age: " + age)
Convert the number to a string first, or use an f-string.
print("Age: " + str(age))
String Repetition
Python allows strings to be repeated using the
multiplication operator *.
line = "-" * 20
print(line)
--------------------
Another example:
word = "Hi "
print(word * 3)
Hi Hi Hi
String Membership
The membership operators in and
not in can be used to search for text
inside a string.
message = "Python is powerful"
print("Python" in message)
print("Java" in message)
print("Java" not in message)
True
False
True
word = "Python"
print("Python" in word)
print("python" in word)
The first result is True and the
second is False.
Escape Characters
Escape characters allow us to include special characters or formatting inside strings.
New Line
print("Hello\nWorld")
Hello
World
Tab
print("Name:\tAli")
print("Age:\t25")
Name: Ali
Age: 25
Quotes Inside Strings
message = "He said \"Python is fun!\""
print(message)
He said "Python is fun!"
Backslash
path = "C:\\Users\\Student"
print(path)
C:\Users\Student
Raw Strings
A raw string tells Python to treat backslashes mostly as ordinary characters instead of interpreting them as escape sequences.
path = r"C:\Users\Student\Documents"
print(path)
C:\Users\Student\Documents
Raw strings are particularly useful when working with Windows paths and regular expressions.
Important Detail
A raw string is not a completely different data
type. It is still an ordinary Python string;
the r prefix changes how backslashes
are interpreted while the literal is created.
String Immutability
Python strings are immutable. This means that once a string object is created, its individual characters cannot be changed directly.
word = "Python"
# This is not allowed:
# word[0] = "J"
Instead, create a new string.
word = "Python"
word = "J" + word[1:]
print(word)
Jython
String operations generally create new string objects rather than modifying the original string in place.
Comparing Strings
Strings can be compared using comparison operators.
a = "apple"
b = "apple"
c = "banana"
print(a == b)
print(a == c)
print(a != c)
True
False
True
Python also supports alphabetical-style comparisons based on Unicode code points.
print("apple" < "banana")
True
Uppercase and lowercase characters have different Unicode code points, so comparisons can produce results that may surprise beginners.
Whitespace in Strings
Spaces, tabs, and line breaks are characters too. This matters when processing user input or data.
name = " Ali "
print(name)
print(len(name))
The spaces at the beginning and end are part of the string.
Later, you'll learn useful string methods such as
strip() to remove unwanted whitespace.
Coming Later
String methods such as upper(),
lower(), replace(),
split(), and strip()
will be covered in a dedicated lesson.
Common String Mistakes
Mistake 1 — Forgetting Quotation Marks
# Incorrect
# name = Ali
# Correct
name = "Ali"
Mistake 2 — Mixing String and Integer Values
age = 25
# Incorrect:
# print("Age: " + age)
Convert the integer:
print("Age: " + str(age))
Mistake 3 — Expecting Strings to Change in Place
Remember that strings are immutable.
Mistake 4 — Ignoring Case
answer = "YES"
print(answer == "yes")
False
Practice Exercises
Exercise 1 — Create a Profile
Create variables for your name, city, and favorite programming language. Print each value.
Exercise 2 — String Length
Create a string containing your favorite quote and
use len() to find its length.
Exercise 3 — Concatenation
Create first-name and last-name variables and combine them into a full name.
Exercise 4 — Repetition
Create a decorative line using the multiplication operator.
print("*" * 30)
Exercise 5 — Membership
Create a sentence and check whether the word
"Python" exists inside it.
Exercise 6 — Escape Characters
Print a three-line message using \n.
Mini Challenge — Student Profile Generator
Build a small program that creates a formatted student profile using strings.
Your program should:
- Store a student's name.
- Store their city.
- Store their favorite subject.
- Calculate the length of their name.
- Display a clean profile.
name = "Ali"
city = "Multan"
subject = "Python"
print("=" * 30)
print("STUDENT PROFILE")
print("=" * 30)
print("Name:", name)
print("City:", city)
print("Favorite Subject:", subject)
print("Name Length:", len(name))
print("=" * 30)
==============================
STUDENT PROFILE
==============================
Name: Ali
City: Multan
Favorite Subject: Python
Name Length: 3
==============================
Take It Further
Modify the program to collect the student's
information using input().
You've reached the end of this lesson.
Review the examples, open the Practice Lab, and mark this lesson complete when you're ready.