Strings in Python
Table of Contents
In the last lesson, we learned numbers in Python. Now letβs learn how Python stores and works with text.
So far, we have worked with numbers. But most of the time, we work with text.
Names. Addresses. Messages. Passwords. Sentences. All of that is text.
In Python, text is called a string.
A string is just a sequence of characters. Letters, numbers, symbols, spaces β anything we can type. If it is inside quotes, it is a string.
βοΈ How to Create a String in Python
We create a string by putting text inside quotes.
name = "Alex"message = 'Hello, how are you?'We can use single quotes or double quotes. Both work. Python does not care.
But letβs be consistent. Letβs pick one style and stick with it. Most Python programmers use double quotes.
π¬ When to Use Which Quotes in Python
Here is a useful tip.
If our text contains a single quote, we use double quotes around it.
message = "It's a nice day"See the apostrophe in βItβsβ? If we used single quotes, it would break.
message = 'It's a nice day' # Error!Python would think the string ends at It. And then s a nice day makes no sense.
So when our text has an apostrophe, letβs use double quotes.
Similarly, if our text contains double quotes, we use single quotes.
quote = 'He said "Hello" to me'That works fine.
π Triple Quotes for Long Text in Python
If we have a long string that spans multiple lines, we use triple quotes.
message = """This is a long message.It spans multiple lines.And it works perfectly."""We can use three single quotes or three double quotes. Both work.
message = '''This also works.Multiple lines.No problem.'''Triple quotes are great for long text. Like paragraphs. Or documentation.
π€ Escape Characters in Python Strings
Sometimes we need special characters in our string. Like a new line. Or a tab. Or a quote inside a quote.
We use escape characters. They start with a backslash \.
print("Hello\nWorld")Output
HelloWorld\n means new line.
print("Name:\tAlex")Output
Name: Alex\t means tab.
print("He said \"Hello\"")Output
He said "Hello"\" means a literal double quote inside a double-quoted string.
Here are the common ones:
| Escape | Meaning |
|---|---|
\n | New line |
\t | Tab |
\\ | Backslash |
\' | Single quote |
\" | Double quote |
π Strings Are Immutable in Python
This is important. Strings cannot be changed.
Once we create a string, it stays the same. We cannot change a character inside it.
name = "Alex"name[0] = "B" # Error!Python will give us an error:
TypeError: 'str' object does not support item assignmentWe cannot change a string in place. We can only create a new string.
name = "Alex"new_name = "B" + name[1:]print(new_name)Output
BlexSee? We created a new string. We did not change the old one.
This is called immutability. It means βcannot be changed.β
Strings are immutable. Numbers are immutable too. But lists are not. We will learn about that later.
π Joining Strings in Python
We can join strings with the + operator.
first = "Alex"last = "Smith"full = first + " " + lastprint(full)Output
Alex SmithNotice the " " in the middle. That adds a space between the names.
Without it:
full = first + lastprint(full)Output
AlexSmithSo letβs remember to add spaces when we need them.
π Repeating Strings in Python
We can repeat a string with the * operator.
print("Ha" * 3)Output
HaHaHaprint("-" * 20)Output
--------------------This is handy for making separators in our output.
π String Length in Python
How many characters are in a string?
We use the len() function.
name = "Alex"print(len(name))Output
4Because βAlexβ has 4 characters: A, l, e, x.
message = "Hello, world!"print(len(message))Output
13Spaces count too. And punctuation. Everything counts.
π’ Accessing Characters in Python Strings
We can get a single character from a string using its position. This is called indexing.
name = "Alex"print(name[0])Output
AWait. Why 0? Why not 1?
Because in Python, counting starts at 0.
- First character is at index 0
- Second character is at index 1
- Third character is at index 2
- And so on
name = "Alex"print(name[0]) # Aprint(name[1]) # lprint(name[2]) # eprint(name[3]) # xThis is a bit weird at first. But we get used to it. Every programmer in the world uses 0-based indexing. It is just how it works.
π Negative Indexing in Python Strings
We can also count from the end using negative numbers.
name = "Alex"print(name[-1]) # x (last character)print(name[-2]) # e (second from last)print(name[-3]) # lprint(name[-4]) # A-1 means last. -2 means second from last. And so on.
This is very handy. We do not need to know the length. Just use -1 for the last character.
π Checking If Something Is in a String
We can check if a word or character is inside a string.
message = "Hello, world!"print("world" in message)Output
Trueprint("python" in message)Output
FalseWe use in to check. It gives us True or False.
We can also use not in to check the opposite.
print("python" not in message)Output
Trueπ§ͺ Python Strings: A Real-Life Example
Letβs build a simple program that uses strings.
first_name = "Alex"last_name = "Smith"age = 25
full_name = first_name + " " + last_namemessage = "Hello, " + full_name + "! You are " + str(age) + " years old."print(message)Output
Hello, Alex Smith! You are 25 years old.Wait. What is str(age)?
That converts the number 25 into the string β25β. Because we cannot add a number to a string directly.
print("Age: " + 25) # Error!We have to convert it first.
print("Age: " + str(25)) # WorksBut there is a better way. We will learn about f-strings later. They make this much easier.
β οΈ Common Mistakes with Python Strings
π§ Mistake 1: Forgetting Quotes
name = Alex # Error!So what do we do? We add quotes.
name = "Alex"π₯ Mistake 2: Mixing Quotes
name = "Alex' # Error!So what do we do? We match the quotes.
name = "Alex"Or:
name = 'Alex'π Mistake 3: Trying to Change a String
name = "Alex"name[0] = "B" # Error!So what do we do? We create a new string.
name = "B" + name[1:]β Mistake 4: Adding String and Number
age = 25print("Age: " + age) # Error!So what do we do? We convert the number to a string.
print("Age: " + str(age))Or we use a comma:
print("Age:", age)Next, we will learn about Boolean Values so we can continue step by step.