A string is a sequence of characters, such as a word, a sentence or a phone number. You use strings in almost every Python program. This lesson covers how to create strings, access characters, slice them, join them and format them, with an output for every example. For the full list of string methods, see our lesson on useful string methods.
Try every example in our online Python compiler.
Create a string
A string is written inside single quotes, double quotes or triple quotes. Triple quotes let a string run over several lines.
s1 = 'Python'
s2 = "Hello"
s3 = '''Line one
Line two'''
print(s1, s2)
print(s3)
print(type(s1))Output:
Python Hello
Line one
Line two
<class 'str'>Access characters by index
Each character has an index. Counting starts at 0 from the left, and negative indexes count from the end.
Character | P | y | t | h | o | n |
|---|---|---|---|---|---|---|
Index | 0 | 1 | 2 | 3 | 4 | 5 |
Negative index | -6 | -5 | -4 | -3 | -2 | -1 |
name = 'Python'
print(name[0])
print(name[3])
print(name[-1])
print(name[-2])Output:
P
h
n
oSlice a string
Use string[start:stop:step] to get part of a string. The start index is included, and the stop index is not.
name = 'Python'
print(name[0:3])
print(name[2:])
print(name[:4])
print(name[::2])
print(name[::-1])Output:
Pyt
thon
Pyth
Pto
nohtyPname[::-1] reverses the string, which is a handy trick for palindrome programs.
Length of a string
print(len('Python'))
print(len('Hello World'))Output:
6
11Spaces count as characters, so ‘Hello World’ has 11.
Strings cannot be changed
Strings are immutable. You cannot change one character in place. Instead, build a new string.
name = 'Python'
try:
name[0] = 'J'
except TypeError as e:
print('TypeError:', e)
new_name = 'J' + name[1:]
print(new_name)Output:
TypeError: 'str' object does not support item assignment
JythonJoin, repeat and search
print('Hello' + ' ' + 'World')
print('ab' * 3)
print('Py' in 'Python')
print('py' in 'Python')Output:
Hello World
ababab
True
FalseThe in operator is case-sensitive, so ‘py’ is not found in ‘Python’.
Escape characters
A backslash \ lets you add special characters to a string.
Code | Meaning |
|---|---|
\n | New line |
\t | Tab |
‘ | Single quote |
\ | Backslash |
print('He said \'hi\'')
print('Col1\tCol2')
print('Line1\nLine2')
print('C:\\temp')
print(r'C:\temp')Output:
He said 'hi'
Col1 Col2
Line1
Line2
C:\temp
C:\tempA string that starts with r (a raw string) treats backslashes as normal characters. It is useful for file paths and regular expressions.
Format strings
The easiest way to put values inside a string is an f-string. Put f before the opening quote, and write the value inside curly braces. F-strings need Python 3.6 or newer.
name = 'Asha'
age = 20
price = 49.5
print(f'My name is {name} and I am {age} years old.')
print(f'Price: {price:.2f}')
print(f'{age + 1} next year')
print(f'{1234567:,}')Output:
My name is Asha and I am 20 years old.
Price: 49.50
21 next year
1,234,567{price:.2f} shows the number with 2 digits after the decimal point, and {number:,} adds thousands separators. You can also use the format() method:
print('My name is {} and I am {} years old.'.format('Asha', 20))
print('{0} {1} {0}'.format('a', 'b'))Output:
My name is Asha and I am 20 years old.
a b aCommon string methods
text = ' Hello, World '
print(text.strip())
print('hello world'.title())
print('hello world'.capitalize())
print('apple,banana,cherry'.split(','))
print('-'.join(['a', 'b', 'c']))
print('banana'.replace('a', 'o'))
print('banana'.find('n'))
print('banana'.find('z'))
print('banana'.count('a'))
print('python'.startswith('py'), 'python'.endswith('on'))
print('123'.isdigit(), 'abc'.isalpha(), 'abc123'.isalnum())Output:
Hello, World
Hello World
Hello world
['apple', 'banana', 'cherry']
a-b-c
bonono
2
-1
3
True True
True True Truestrip() removes spaces from both ends. find() returns the index of the first match, or -1 if there is none. upper() and lower() change the case of a string.
Loop through a string
for ch in 'Hi!':
print(ch)Output:
H
i
!Common mistakes
1. Adding a string and a number.
print('Age: ' + 20)
TypeError: can only concatenate str (not "int") to strThe exact wording of the message can differ between Python versions. Convert the number first, or use an f-string:
print('Age: ' + str(20))
Age: 202. Trying to change a character in a string. Strings are immutable, so create a new string instead.
3. Forgetting that string methods return a new string. text.upper() does not change text. Save the result: text = text.upper().
Practice questions
- For txt = ‘Welcome to Python’, print the last 6 characters.
- Print the second word of txt.
- Count the words in txt.
- Reverse txt.
- Print txt in capital letters.
Answers
txt = 'Welcome to Python'
print(txt[-6:]) # Python
print(txt.split()[1]) # to
print(len(txt.split())) # 3
print(txt[::-1]) # nohtyP ot emocleW
print(txt.upper()) # WELCOME TO PYTHONSummary
- A string is a sequence of characters, and it is immutable.
- Use indexes and slices to get characters and parts of a string.
- Use f-strings to build text with values.
- String methods return new strings, so save the result.
