Python String Basics

In the last lesson you learned Recursion in Python. There a function calls itself to solve a problem in smaller pieces. Now we slow down and look closely at something you have already used a little. We mean text. Almost every program touches text at some point. A name, a message, a file path, a line of output. In Python that text is called a string. And there is more to it than just putting words in quotes.

πŸ€” Why Strings Need a Closer Look

You have already printed a few strings. Maybe you stored one in a variable. So why come back to them?

Because the moment you try to do real work, small questions pop up fast. How do you put a quote mark inside a quoted string? How do you write text that spans many lines? How do you check how long a piece of text is? And why does changing a string sometimes behave in a way you did not expect?

A string is simply a piece of text. The fix for all those small questions is the same. Learn the few rules strings follow. Then they stop surprising you.

🧩 What a String Really Is

Think of a string like a row of beads on a wire. Each bead is one character. And the order matters. The word Hello is five beads in a row: H, e, l, l, o. Python keeps them in that exact order. That is what makes text behave predictably.

You create a string by wrapping text in quotes. Python gives you a few ways to do that.

✍️ Three Ways to Write Quotes

You can use single quotes, double quotes, or triple quotes. Here is each one in action.

single = 'Hello there'
double = "Hello there"
triple = """Hello there"""
print(single)
print(double)
print(triple)

All three print the same thing.

Output

Hello there
Hello there
Hello there

So why have three styles? Because the type of quote you pick lets you include the other type as plain text.

Say Riya wants to print a sentence that contains an apostrophe. An apostrophe is the same character as a single quote. If she wraps the whole sentence in single quotes, Python gets confused about where the string ends.

# ❌ Avoid: the apostrophe in "Riya's" ends the string too early
message = 'Riya's lunch is ready'
# βœ… Good: wrap in double quotes so the apostrophe is just text
message = "Riya's lunch is ready"
print(message)

Output

Riya's lunch is ready

The same trick works the other way. If your text contains double quotes, wrap it in single quotes.

quote = 'Alex said "good morning" to the team'
print(quote)

Output

Alex said "good morning" to the team

Tip

Pick one style, single or double, and use it everywhere in your project for normal text. Switch to the other only when the text itself contains that quote character. Many Python teams default to double quotes.

πŸ“œ Triple Quotes for Many Lines

Single and double quotes work for one line of text. But what if Arjun wants to store a short note that runs across several lines? That is where triple quotes earn their place.

Wrap the text in three quote marks (either """ or ''') and the line breaks you type are kept exactly as they are.

note = """Dear team,
The meeting moved to 3 PM.
Please update your calendar.
Thanks,
Arjun"""
print(note)

The output keeps every line break you wrote.

Output

Dear team,
The meeting moved to 3 PM.
Please update your calendar.
Thanks,
Arjun

This is great for longer messages, blocks of help text, or anything where the shape of the lines matters.

⛓️ Escape Sequences

Now, what if you want a line break or a tab inside a normal single-line string, without using triple quotes? You use an escape sequence. An escape sequence is a backslash \ followed by one letter that stands for a special character.

The most useful one is \n. It means β€œstart a new line” right at that spot.

print("Line one\nLine two")

Python turns \n into an actual line break.

Output

Line one
Line two

Here are the escape sequences you will reach for most often.

Escape What it means
\n Newline (start a new line)
\t Tab (a wide horizontal space)
\\ A single backslash character
\" A double quote inside a double-quoted string

Here they are together in one example.

print("Name:\tAlex")
print("City:\tBerlin")
print("Path: C:\\Users\\Alex")
print("She said \"hello\" and waved")

Read the output line by line and match each one back to the code.

Output

Name: Alex
City: Berlin
Path: C:\Users\Alex
She said "hello" and waved

So what is happening here?

  • \t pushes the text after it to the next tab stop, so the values line up.
  • \\ prints one real backslash. You need two in the code because a single \ starts an escape.
  • \" lets a double quote sit inside a double-quoted string without ending it early.

Caution

A backslash that is not part of a known escape can cause trouble or a warning. When you mean a literal backslash, always write \\. This matters a lot for Windows file paths.

πŸ“ Measuring Length with len()

A very common question is β€œhow many characters is this text?” Maybe Riya is checking that a username is not too long. Or that a password is long enough. The len() function answers that. You give it a string. It gives you back the count of characters.

name = "Riya"
print(len(name))
password = "open sesame"
print(len(password))

Output

4
11

Notice that len() counts every character, including spaces. The text open sesame is eleven characters because the space in the middle counts too.

Note

An empty string, written as "", has a length of 0. It is a real string. It just holds no characters yet.

βž• Joining Strings with +

Often you have two pieces of text and you want them as one. Sticking strings together end to end is called concatenation. The + symbol does it.

first = "Good"
second = "morning"
greeting = first + " " + second
print(greeting)

Output

Good morning

Notice the " " in the middle. The + joins the pieces with nothing between them. So if you want a space, you add it yourself as its own little string. Without it you would get Goodmorning.

One catch. The + only joins string to string. If you try to join a string and a number directly, Python stops you.

age = 30
# ❌ Avoid: you cannot add a number straight onto a string
# message = "Age: " + age
# βœ… Good: turn the number into a string first with str()
message = "Age: " + str(age)
print(message)

Output

Age: 30

For joining lots of pieces, especially with variables, f-strings are usually cleaner than +. You saw those earlier. Here + is the simple, direct tool for sticking a couple of strings together.

πŸ”’ Strings Are Immutable

Here is the idea that surprises people the most. A string is immutable. Immutable means it cannot be changed after you create it. Once those beads are on the wire, you cannot replace a single bead.

Try to change one character directly and Python refuses.

word = "cat"
# ❌ Avoid: you cannot edit a character in place
word[0] = "b"

This raises an error.

Output

Traceback (most recent call last):
File "main.py", line 2, in <module>
word[0] = "b"
~~~~^^^
TypeError: 'str' object does not support item assignment

So how do people β€œchange” text all the time? They do not edit the old string. They build a brand new one and point the variable at it.

word = "cat"
word = "b" + word[1:]
print(word)

Output

bat

Here word[1:] grabs everything from the second character onward, which is at. Then "b" + "at" makes a fresh string bat. And word now points at that new string. The original cat was never edited. It was simply replaced.

This is not a limitation to fight. It actually makes strings safe and predictable. When you pass a string around your program, you know nobody can secretly change it under you.

⚠️ Common Mistakes

A few slip-ups catch almost everyone at the start.

  • Using the wrong quote style so an apostrophe ends the string early. Wrap the text in double quotes instead.
  • Forgetting the space when joining with +, so "Good" + "morning" comes out as Goodmorning.
  • Writing a single \ for a Windows path. Use \\ so it is a real backslash and not an accidental escape.
  • Trying to add a number onto a string with +. Convert it first with str().
  • Expecting word[0] = "x" to work. Strings are immutable, so build a new string instead.

βœ… Best Practices

  • Pick one quote style for normal text and stay consistent across your project.
  • Reach for triple quotes when text genuinely spans several lines, not for single-line text.
  • Prefer f-strings over long chains of + once you are mixing in variables and numbers.
  • Use len() to check length instead of guessing or counting by eye.
  • Remember that any β€œedit” to a string actually makes a new string, so assign the result back to a variable.

🧩 What You’ve Learned

βœ… A string is an ordered row of characters, created with single, double, or triple quotes.

βœ… Triple quotes let text span many lines and keep your line breaks exactly as typed.

βœ… Escape sequences like \n, \t, \\, and \" put special characters inside a string.

βœ… len() gives the number of characters in a string, spaces included.

βœ… The + symbol joins strings, but you add spaces yourself and convert numbers with str() first.

βœ… Strings are immutable, so you never edit one in place. You build a new string and reassign it.

Check Your Knowledge

Test what you learned. Pick an answer for each question, then click Check.

  1. 1

    Why would you wrap a sentence containing an apostrophe in double quotes?

    Why: An apostrophe is the same character as a single quote, so wrapping the text in double quotes lets it sit inside as plain text.

  2. 2

    What does the escape sequence \t produce?

    Why: The \t escape sequence inserts a tab, which pushes the following text to the next tab stop.

  3. 3

    What is the length of the string "open sesame" according to len()?

    Why: len() counts every character including the space in the middle, so the total is 11.

  4. 4

    What happens when you try word[0] = "b" on a string?

    Why: Strings are immutable, so you cannot assign to a single position. You must build a new string instead.

πŸš€ What’s Next?

You can now create, measure, and join strings. And you understand why they never change in place. Next you will meet the built-in tools that do real work on text, like changing case, searching, and trimming spaces.

String Methods

Share & Connect