Python string
last modified November 19, 2026 Python 3.15
In this article we introduce strings in Python. It covers the basics of the
str type and links to the articles that treat individual string
operations in detail.
A string in Python is an immutable sequence of Unicode code points. Strings
have the type str. Being a sequence, a string supports indexing,
slicing, iteration, and the len function; being immutable, it
cannot be changed after it is created. Every operation that seems to modify a
string returns a new one.
String literals
String literals are written in single or double quotes. Both forms create the same kind of object.
#!/usr/bin/python
a = 'an old falcon'
b = "an old falcon"
print(a == b)
print("It's a nice day")
print('He said: "Hello"')
print('It\'s a nice day')
c = '''one
two'''
print(c)
print(type(a))
print(repr(str()), len(''))
Single and double quotes are equivalent; we pick the one that does not appear
in the text, or escape the inner quote with a backslash. Triple quotes create
strings that span several lines; they are covered in
Python multiline strings. Calling
str without arguments gives an empty string.
$ python literals.py True It's a nice day He said: "Hello" It's a nice day one two <class 'str'> '' 0
Escape sequences
A backslash starts an escape sequence, which stands for a character that is hard to type or see.
#!/usr/bin/python
print('sky\tblue\nsea\tgreen')
print('C:\\Users\\jano')
print('\x41\u00e9\N{GREEK SMALL LETTER ALPHA}')
path = r'C:\Users\new'
print(path)
print(len('\n'), len(r'\n'))
The common escapes are \n (new line), \t (tab),
\\ (backslash), and \' and \" (quotes).
A character can also be given by its code: \x41 takes two hex
digits, \u00e9 four, and \N{...} takes the Unicode
name. In a raw string, prefixed with r, backslashes are ordinary
characters; this is useful for Windows paths and
regular expressions. That is why
len(r'\n') is 2.
$ python escapes.py sky blue sea green C:\Users\jano Aéα C:\Users\new 1 2
Characters and code points
Every character of a string is a Unicode code point, a number. The
ord function returns the number of a character and
chr does the reverse.
#!/usr/bin/python
print(ord('a'), ord('é'), ord('€'))
print(chr(97), chr(233), chr(8364))
print(hex(ord('€')))
word = 'Zürich'
for c in word:
print(c, ord(c))
The letters of the English alphabet have the same numbers as in ASCII.
Accented letters and symbols such as the euro sign have higher numbers;
€ is U+20AC. Python has no separate character type: iterating
over a string yields strings of length one.
$ python code_points.py 97 233 8364 a é € 0x20ac Z 90 ü 252 r 114 i 105 c 99 h 104
String length
The len function returns the number of code points in a
string, which is not always the number of bytes or the number of characters
a reader sees.
#!/usr/bin/python
words = ['falcon', 'Zürich', 'čerešňa', '日本語', '🦅']
for word in words:
print(word, len(word), len(word.encode()))
e1 = 'caf\u00e9'
e2 = 'cafe\u0301'
print(e1, e2, len(e1), len(e2), e1 == e2)
We print each word with its length and the number of bytes in its UTF-8
encoding. ASCII letters take one byte, Slovak letters with diacritics two,
Japanese characters three, and the emoji four. The last line shows that
é can be written as one code point or as e followed
by a combining accent. The two strings look the same but differ in length and
are not equal. Encodings are covered in
Python encode/decode; comparing such
strings with normalization in
Python compare strings.
$ python length.py falcon 6 6 Zürich 6 7 čerešňa 7 10 日本語 3 9 🦅 1 4 café café 4 5 False
Indexing and iteration
Characters are accessed by index, starting from zero. Negative indexes count from the end.
#!/usr/bin/python
word = 'falcon'
print(word[0], word[1], word[-1])
print(word[1:4])
for c in word:
print(c, end=' ')
print()
for i, c in enumerate(word, start=1):
print(i, c, end=' | ')
print()
try:
word[6]
except IndexError as e:
print('error:', e)
word[-1] is the last character and word[1:4] is a
slice with the characters at indexes 1 to 3. A for loop goes
over the characters; enumerate adds a counter. An index past the
end raises IndexError. Slices, steps, and negative bounds are
covered in Python string slicing.
$ python indexing.py f a n alc f a l c o n 1 f | 2 a | 3 l | 4 c | 5 o | 6 n | error: string index out of range
Immutability
Strings cannot be changed in place. We create new strings instead.
#!/usr/bin/python
word = 'falcon'
try:
word[0] = 'F'
except TypeError as e:
print('error:', e)
new = 'F' + word[1:]
print(new, word)
upper = word.upper()
print(upper, word)
other = word
word += 's'
print(word, other)
Assigning to an index raises TypeError. To change the first
letter, we build a new string from a new letter and a slice. Methods such as
upper return a new string and leave the original alone. The
augmented assignment word += 's' also creates a new string and
binds the name word to it; the variable other still
refers to the old one.
$ python immutable.py error: 'str' object does not support item assignment Falcon falcon FALCON falcon falcons falcon
String operators
Strings support several operators: + concatenates,
* repeats, in tests membership, and comparison
operators compare strings.
#!/usr/bin/python
a = 'sky'
b = 'blue'
print(a + ' ' + b)
print(a * 3)
print('-' * 20)
print('k' in a, 'sea' not in b)
print('apple' < 'banana', 'Zebra' < 'apple')
print(a == 'sky', a != 'Sky')
print(max('falcon'), min('falcon'), sorted('falcon'))
The in operator finds a substring, not only a single character.
Strings are compared character by character by their code points, so all
uppercase letters sort before lowercase ones and 'Zebra' < 'apple'
is true. The built-in functions max, min, and
sorted work on the characters of a string. More on joining
strings is in Python add strings; on
comparisons in Python compare strings.
$ python operators.py sky blue skyskysky -------------------- True True True True True True o a ['a', 'c', 'f', 'l', 'n', 'o']
Converting to and from strings
Python does not convert numbers to strings automatically. We use the
str and int functions.
#!/usr/bin/python
print(str(42) + ' items')
print(str(3.5), str(True), str([1, 2]))
age = '23'
print(int(age) + 1)
try:
print('age: ' + 23)
except TypeError as e:
print('error:', e)
s = 'tab\there'
print(str(s))
print(repr(s))
The str function converts any object to a string. Adding a
number to a string raises TypeError. The repr
function returns the representation of a string as it would be written in
code, with quotes and escapes; this is handy for spotting tabs and trailing
spaces. Details are in Python int to string
and Python string to number.
$ python conversion.py 42 items 3.5 True [1, 2] 24 error: can only concatenate str (not "int") to str tab here 'tab\there'
Character tests
String methods starting with is test what kind of characters a
string contains.
#!/usr/bin/python
values = ['falcon', 'Falcon7', '2026', ' ', 'čerešňa', 'hello world', '']
for v in values:
print(f'{v!r:15} alpha={v.isalpha()!s:5} alnum={v.isalnum()!s:5} '
f'digit={v.isdigit()!s:5} space={v.isspace()}')
isalpha is true when all characters are letters, including
letters with diacritics; isalnum also allows digits. A space
makes both false. All test methods return False for an empty
string. The differences between isdigit,
isdecimal, and isnumeric are explained in
Python string to number.
$ python char_tests.py 'falcon' alpha=True alnum=True digit=False space=False 'Falcon7' alpha=False alnum=True digit=False space=False '2026' alpha=False alnum=True digit=True space=False ' ' alpha=False alnum=False digit=False space=True 'čerešňa' alpha=True alnum=True digit=False space=False 'hello world' alpha=False alnum=False digit=False space=False '' alpha=False alnum=False digit=False space=False
String methods
The str type has about fifty methods. The example shows a few of
the most common ones.
#!/usr/bin/python
text = ' An old Falcon, an old Owl '
print(text.strip())
print(text.lower())
print(text.count('old'))
print(text.find('Falcon'))
print(text.replace('old', 'young'))
print(text.split())
print(text.startswith(' An'))
clean = text.strip().lower().replace(',', '')
print(clean.split())
print(text)
Each method returns a new value, so calls can be chained, as in the
clean line. The last line shows that the original string is
unchanged. The common methods have their own articles:
strip,lstrip,rstrip,removeprefix– Python strip stringsplit,partition,splitlines– Python split stringjoin– Python join stringfind,index,count,startswith– Python find substringreplace– Python replace stringupper,lower,title– Python string caseljust,center,zfill– Python pad stringtranslate,maketrans– Python translate and maketrans
$ python methods.py An old Falcon, an old Owl an old falcon, an old owl 2 9 An young Falcon, an young Owl ['An', 'old', 'Falcon,', 'an', 'old', 'Owl'] True ['an', 'old', 'falcon', 'an', 'old', 'owl'] An old Falcon, an old Owl
Formatting strings
Formatting inserts values into a string. The modern way is the f-string, a
literal prefixed with f.
#!/usr/bin/python
name = 'falcon'
speed = 389.5
count = 3
print(f'The {name} reaches {speed} km/h')
print(f'{count} {name}s')
print(f'{name.upper()} {speed:.0f} km/h')
print(f'{name:>10}|{name:<10}|{name:^10}|')
print(f'{speed=}')
print('The {} reaches {} km/h'.format(name, speed))
print('The %s reaches %.1f km/h' % (name, speed))
Expressions in curly brackets are evaluated and inserted. After a colon comes
a format specification: .0f rounds to no decimal places,
>10, <10, and ^10 align the value
in ten characters. The = specifier prints the expression as well
as its value. The last two lines show the older format method and
the % operator, which are still found in existing code. See
Python f-string and
Python template strings.
$ python formatting.py
The falcon reaches 389.5 km/h
3 falcons
FALCON 390 km/h
falcon|falcon | falcon |
speed=389.5
The falcon reaches 389.5 km/h
The falcon reaches 389.5 km/h
Text statistics
The last example combines the basics into a program that prints statistics about a short text.
#!/usr/bin/python
import string
from collections import Counter
text = '''\
Python strings are immutable sequences of Unicode code points.
Strings support indexing, slicing, and many methods!
Is 3.15 the newest version? Yes.
'''
letters = [c.lower() for c in text if c.isalpha()]
digits = sum(c.isdigit() for c in text)
spaces = sum(c.isspace() for c in text)
words = [w.strip(string.punctuation) for w in text.split()]
sentences = sum(w[-1] in '.!?' for w in text.split())
print('characters:', len(text))
print('letters: ', len(letters))
print('digits: ', digits)
print('whitespace:', spaces)
print('lines: ', len(text.splitlines()))
print('words: ', len(words))
print('sentences: ', sentences)
print('longest: ', max(words, key=len))
vowels = sum(c in 'aeiou' for c in letters)
print('vowels: ', vowels)
print('top letters:', Counter(letters).most_common(3))
We collect the letters with a comprehension and count digits and whitespace
by summing booleans (True counts as 1). Words come from
split with punctuation stripped. A word that ends with a period,
an exclamation mark, or a question mark ends a sentence, which also keeps the
3.15 version number from counting as one. max with
key=len finds the longest word, and a Counter the
most common letters.
$ python text_stats.py
characters: 149
letters: 117
digits: 3
whitespace: 22
lines: 3
words: 22
sentences: 4
longest: immutable
vowels: 41
top letters: [('s', 14), ('e', 14), ('n', 13)]
Source
Text sequence type – Python documentation
String and bytes literals – Python language reference
In this article we have introduced Python strings: literals, escapes, code points, indexing, immutability, operators, conversions, methods, and formatting. For binary data, see Python bytes; the string articles are listed in the Python tutorials index.
Author
List all Python tutorials.