Strings in Python
Table of Contents + β
In the last lesson you learned Numbers in Python. Numbers are great for counting and math. But a lot of what you work with is not numbers at all. It is words. A name, a message, a city. For that, Python gives you the string.
π€ Why do we need strings?
Think about almost any app you use. WhatsApp shows messages. YouTube shows video titles. Amazon shows product names. None of that is math. It is all text.
So the problem is simple. You need a way to hold text in your program. A name like βAlexβ. A sentence. A whole paragraph.
That is exactly what a string is. A string is just text, wrapped in quotes.
π What is a string?
A string is text wrapped in quotes. The moment you put quotes around something, Python treats it as text.
Here is a string stored in a variable so we can use it.
name = "Alex"print(name)Output
AlexLetβs read that line by line:
"Alex"is the string. The quotes tell Python βthis is textβ.nameis a variable holding that text.print(name)shows it on the screen.
Think of a string like a label on a box. The label can say anything you want. A name, a price tag, a note. Python does not try to understand the words inside. It just holds the text for you.
π€ Single or double quotes?
You can wrap a string in single quotes '...' or double quotes "...". Both work the same way. Python does not care which one you pick.
This first line uses double quotes. The second line uses single quotes. They both make a normal string.
city = "Paris"country = 'France'print(city)print(country)Output
ParisFranceSo why have both? Because sometimes the text itself contains a quote. Look at this:
# β
Good: the text has an apostrophe, so wrap it in double quotesmessage = "It's a sunny day"print(message)The word It's has an apostrophe, which is a single quote. If you wrapped the whole thing in single quotes, Python would get confused about where the text ends. So you use double quotes on the outside instead. Just pick the quote style that does not clash with the text inside.
Just stay consistent
Both quote styles are fine. So pick one and stick with it across your code. Most Python programmers use double quotes by default. They switch to single quotes only when the text contains a " character.
β Joining strings together
Often you have two pieces of text and you want them as one. Joining strings end to end is called concatenation. You do it with the + sign.
Here we join a first name and a last name into a full name.
first = "Riya"last = "Sharma"full_name = first + " " + lastprint(full_name)Output
Riya SharmaLook closely at the middle part, first + " " + last:
firstis the textRiya." "is a string with just a space in it. Without this, you would getRiyaSharmastuck together.lastis the textSharma.
So + glues strings together in order, left to right. Notice the + here does not add like it does with numbers. With strings, it joins.
You can't join text and a number with +
"Age: " + 25 will crash. Python will not mix a string and a number with +. First you turn the number into a string with str(25). That gives you "25". So "Age: " + str(25) works and gives Age: 25.
βοΈ Repeating a string
The * sign repeats a string. You give it the text and how many times to repeat it.
This makes a line of dashes without typing each one.
line = "-" * 20print(line)print("ha" * 3)Output
--------------------hahahaSo "-" * 20 means βthe dash, twenty timesβ. And "ha" * 3 gives hahaha. This is handy for drawing simple separator lines or repeating a pattern.
π How long is a string?
Sometimes you need to know how many characters a string has. The len() function gives you the length, which is the count of characters.
Here we check the length of a password to see if it is long enough.
password = "secret123"print(len(password))Output
9The word secret123 has nine characters. So len() returns 9. And remember, spaces count too. The string "a b" has a length of 3, not 2. The space in the middle is a character as well.
π’ Reading one character by position
A string is made of characters in a row. You can grab one character by its position. The position number is called the index. You write it in square brackets like [0].
Here is the part that trips people up. Counting starts at 0, not 1. So the first character is at index 0.
This reads the very first character of a word.
word = "Python"print(word[0])print(word[1])Output
PySo word[0] is P, the first character. And word[1] is y, the second one. It feels odd at first that we start at zero. But you get used to it fast. And it is the same in most programming languages.
This is just a first look. Reading a whole range of characters at once, called slicing, comes later in the Strings module. For now, just know you can reach a single character by its position.
π Strings across many lines
A normal string lives on one line. But sometimes you want text that spans several lines, like an address or a short note. For that, you wrap it in triple quotes, """...""".
This stores a small address that keeps its line breaks.
address = """42 Garden StreetGreenfield12345"""print(address)Output
42 Garden StreetGreenfield12345Everything between the triple quotes is kept exactly as you wrote it, line breaks and all. You can use three double quotes """ or three single quotes '''. Both work the same.
π Strings cannot be changed in place
Here is one thing to keep in the back of your mind. Once a string is made, you cannot change a character inside it. We say strings are immutable, which just means βcannot be changedβ.
So this does not work:
name = "Alex"
# β Avoid: trying to change one character in placename[0] = "B" # this crashesYou cannot reach into name and swap the A for a B. Python will raise an error. But do not worry. You can always make a brand new string instead.
name = "Alex"
# β
Good: build a new string and store itname = "B" + name[1:]print(name)Output
BlexSo you do not edit a string. You create a new one and point your variable at it. That is the whole idea behind immutable. This is just a heads-up for now, so it does not surprise you later.
β οΈ Common Mistakes
A few small things catch people when they start with strings. Watch for these.
- Forgetting the space when you join.
"Riya" + "Sharma"givesRiyaSharma, all stuck together. Add a space string in the middle:"Riya" + " " + "Sharma". - Mixing up quotes. If you open with
"you must close with". Do not start with one kind and end with the other. - Counting from one. The first character is at index
0, not1. Soword[1]is the second character, not the first. - Joining text and numbers with
+."Score: " + 10crashes. Turn the number into a string first withstr(10).
# β Avoid: string + numberprint("Score: " + 10)
# β
Good: turn the number into a string firstprint("Score: " + str(10))β Best Practices
- Pick one quote style, usually double quotes, and use it everywhere so your code looks consistent.
- Use
str()to turn a number into a string before you join it with+. - Reach for triple quotes when your text needs to span more than one line.
- Remember strings are immutable. When you need a change, build a new string rather than trying to edit the old one.
π§© What Youβve Learned
You just met the string, the way Python holds text. Here is the short version.
- β
A string is text wrapped in quotes, and single
'...'or double"..."quotes both work. - β
The
+sign joins strings together, and*repeats a string a set number of times. - β
len()tells you how many characters a string has, spaces included. - β
You read one character by its position with square brackets, and counting starts at
0. - β
Triple quotes
"""..."""make text that spans many lines, and strings are immutable, so you make a new one instead of editing in place.
Check Your Knowledge
Test what you learned. Pick an answer for each question, then click Check.
- 1
What is a string in Python?
Why: A string is text wrapped in quotes, like "Alex" or 'Paris'. Python treats whatever is inside the quotes as text.
- 2
What does "ab" * 3 produce?
Why: The `*` sign repeats a string. So "ab" * 3 gives "ababab", the text three times with no spaces.
- 3
What does len("hello") return?
Why: `len()` counts the characters in a string. The word "hello" has 5 characters, so it returns 5.
- 4
In the string "Python", what is at index 0?
Why: Counting starts at 0, so index 0 is the first character. In "Python" that is the letter P.
π Whatβs Next?
You can hold text now. Next, letβs look at a different kind of value, the one that is only ever true or false.