Working with Strings
Learn how to create, combine, format, and manipulate text in Python.
Strings and quotes
A string is any sequence of characters inside quotes. Characters can be letters, numbers, spaces or symbols. Strings are how Python handles text, such as names, messages and passwords. You can use single quotes or double quotes. Both work the same way.
greeting = "Hello, World!"
name = 'Alice'
sentence = "It's a nice day." # use double quotes when the text has a single quote inside
The quotes are not part of the text. They just tell Python where the string starts and stops. If your text contains a single quote, like It's, wrap it in double quotes so Python does not think the string ended early. The opposite also works.
quote = 'She said "hello" to me'
empty = "" # an empty string is allowed
print(quote)
She said "hello" to me
Whatever kind of quote you open with, you must close with the same kind.
Joining strings
You can join two strings using the plus sign. This is called concatenation:
first = "Hello"
second = "World"
result = first + " " + second
print(result) # Hello World
Notice the " " in the middle. Python joins exactly what you give it, so you must add the space yourself. You can also repeat a string with *:
print("ha" * 3) # hahaha
print("-" * 20) # a line of 20 dashes
Remember, you can only join strings with other strings. If you try to join a string and a number, Python gives an error. Convert the number to a string first:
age = 25
message = "I am " + str(age) + " years old."
print(message) # I am 25 years old.
print("I am " + 25 + " years old.")
# TypeError: can only concatenate str (not "int") to str
f-strings, the clean way
Joining strings with + gets messy fast. A much cleaner way is an f-string. Put the letter f before the opening quote, then put variable names inside curly braces right in the text:
name = "Alice"
age = 25
city = "London"
print(f"My name is {name}, I am {age} years old, and I live in {city}.")
My name is Alice, I am 25 years old, and I live in London.
No str() needed. Python turns the numbers into text for you. You can also put whole expressions inside the curly braces:
price = 9.99
quantity = 3
print(f"Total: ${price * quantity:.2f}") # Total: $29.97
The :.2f tells Python to show exactly 2 decimal places. It comes after a colon inside the braces. A few other useful format tricks:
n = 1234567
print(f"{n:,}") # 1,234,567 (adds commas)
ratio = 0.256
print(f"{ratio:.1%}") # 25.6% (shows a percentage)
print(f"{'Hi':>6}") # Hi (right aligned in 6 spaces)
String methods
Strings come with built-in tools called methods. A method is a function that belongs to a value, and you call it with a dot after the variable name:
text = " Hello, World! "
print(text.upper()) # " HELLO, WORLD! "
print(text.lower()) # " hello, world! "
print(text.strip()) # "Hello, World!", removes spaces from both ends
print(text.replace("World", "Python")) # " Hello, Python! "
print(text.strip().startswith("Hello")) # True
print(text.strip().endswith("!")) # True
Two important things to notice. First, you can chain methods, as in text.strip().startswith(...), which runs left to right. Second, methods never change the original string. They give you a new one. Strings are immutable, which means they cannot be changed in place.
name = "alice"
name.upper() # the result is thrown away
print(name) # alice, unchanged
name = name.upper() # store the new string to keep it
print(name) # ALICE
Some more methods worth knowing:
word = "banana"
print(word.count("a")) # 3
print(word.find("n")) # 2, the index of the first n (-1 if missing)
print("hello world".title()) # Hello World
print("123".isdigit()) # True
print("abc".isalpha()) # True
Splitting and joining
split() breaks a string into a list of smaller strings. join() does the opposite and glues a list back into one string.
sentence = "apple,banana,cherry"
fruits = sentence.split(",") # split into a list by comma
print(fruits) # ['apple', 'banana', 'cherry']
words = ["I", "love", "Python"]
result = " ".join(words) # join the list with a space between each item
print(result) # I love Python
The separator you give to split is what Python cuts on. With no separator, split() cuts on any spaces, which is perfect for counting words:
text = "the quick brown fox"
words = text.split()
print(words) # ['the', 'quick', 'brown', 'fox']
print(len(words)) # 4
For join, the string you call it on goes between the items. "-".join(["a", "b", "c"]) gives a-b-c. It is a little backwards at first, but you will get used to it. The list can only hold strings, so convert numbers first.
Length and indexing
Use len() to count the characters in a string. Spaces count too. You can reach single characters using their position number, called the index. The first character is at index 0, not 1:
word = "Python"
print(len(word)) # 6
print(word[0]) # P, the first character
print(word[1]) # y, the second character
print(word[-1]) # n, the last character, negative counts from the end
P y t h o n
0 1 2 3 4 5
-6 -5 -4 -3 -2 -1
Each letter has two positions, one counting from the left and one from the right. Counting from zero feels strange, but nearly every programming language does it. If you ask for an index that does not exist, Python raises an IndexError.
word = "Python"
print(word[6]) # IndexError: string index out of range
The last valid index is always len(word) - 1.
Slicing and searching
Extract part of a string using string[start:end]. The start is included, the end is not:
word = "Python"
print(word[0:3]) # Pyt, positions 0, 1, 2
print(word[2:]) # thon, from position 2 to the end
print(word[:4]) # Pyth, from the start to position 3
A good way to remember this: the end number is where the slice stops, right before that position. The length of the slice is end - start. You can also add a step and use negative numbers:
word = "Python"
print(word[::2]) # Pto, every second character
print(word[::-1]) # nohtyP, the string reversed
print(word[-3:]) # hon, the last three characters
Use the in keyword to check if a piece of text exists inside another string. The answer is True or False:
email = "user@example.com"
print("@" in email) # True
print(".com" in email) # True
print("gmail" in email) # False
The check is case sensitive, so "A" in "apple" is False. Convert both sides with .lower() first when you do not care about capitals.
Special characters and long text
Some characters cannot be typed directly inside a string. For those, Python uses an escape sequence, which starts with a backslash:
\nstarts a new line\tadds a tab\"and\'put a quote inside a string\\prints one backslash
print("Line one\nLine two")
print("Name:\tAlice")
print("She said \"hi\"")
print("C:\\Users\\Alice")
Line one
Line two
Name: Alice
She said "hi"
C:\Users\Alice
For text that runs over several lines, use triple quotes. Everything between them stays exactly as typed, including line breaks:
poem = """Roses are red,
Violets are blue,
Python is fun,
And so are you."""
print(poem)
Finally, a raw string puts an r before the quote and turns off escape sequences. It is handy for Windows file paths: r"C:\new\folder".
Key takeaways
- Strings are text inside single or double quotes
+joins strings,*repeats them, and numbers must be converted withstr()first- f-strings like
f"Hi {name}"are the cleanest way to build text, and:.2fcontrols decimals - Methods such as
upper,lower,strip,replace,splitandjoinreturn new strings and never change the original len()counts characters. Indexes start at 0 and negative indexes count from the end- Slices
[start:end]include the start but not the end inchecks if text is inside another string. Escape sequences like\nhandle special characters