Strings in Python

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

Hello
World

\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:

EscapeMeaning
\nNew line
\tTab
\\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 assignment

We cannot change a string in place. We can only create a new string.

name = "Alex"
new_name = "B" + name[1:]
print(new_name)

Output

Blex

See? 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 + " " + last
print(full)

Output

Alex Smith

Notice the " " in the middle. That adds a space between the names.

Without it:

full = first + last
print(full)

Output

AlexSmith

So 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

HaHaHa
print("-" * 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

4

Because β€œAlex” has 4 characters: A, l, e, x.

message = "Hello, world!"
print(len(message))

Output

13

Spaces 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

A

Wait. 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]) # A
print(name[1]) # l
print(name[2]) # e
print(name[3]) # x

This 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]) # l
print(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

True
print("python" in message)

Output

False

We 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_name
message = "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)) # Works

But 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 = 25
print("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.