Python Strings & String FormattingGet Certified
What Is a String?
A string is a sequence of characters used to store text, such as a name, a sentence, or a password. In Python the string type is called str. Python 3 strings hold Unicode text, so they can contain letters from any language, digits, punctuation, and even emoji. Strings are everywhere: the data you read from users and files, the messages you show on the screen, and the keys of dictionaries are all strings.
- Creating strings: write text inside single quotes, double quotes, or triple quotes.
- Indexing and slicing: pick out one character or a piece of a string by position.
- Immutable: a string cannot be changed after it is created. Methods return new strings.
- Methods: built-in tools such as
upper(),strip(),replace(),split(), andjoin(). - Formatting: f-strings,
format(), and%insert values into text in a controlled way.
Creating Strings
A string literal can be written with single quotes '...' or double quotes "...". Both mean exactly the same, so choose the one that avoids extra escaping. For instance, "It's Python" needs no backslash, while 'It\'s Python' does. Triple quotes, either """...""" or '''...''', create a string that can span several lines, and the line breaks are kept inside the string. The built-in len() function returns the number of characters, and a line break counts as one character.
Try It: Three Ways to Write a String
Click Test My Code. Then add a third line to the multi-line string and run it again to see the length change.
single = 'Hello'
double = "It's Python"
multi = """Line one
Line two"""
print(single, double)
print(multi)
print(len(multi))'Hello' is a string written with single quotes.Line one.Line two is followed by three quotation marks that end the string. The string now holds two lines, separated by a line break.Hello It's Python.Line one and Line two.len() counts 8 characters in each line plus 1 for the line break, so the output is 17.Indexing and Slicing
Every character in a string has a position, called an index. The first character has index 0. Negative indexes count from the end, so -1 is the last character. A slice takes a part of the string with the syntax text[start:stop:step]. The slice includes start but stops before stop. If you leave a value out, Python uses a sensible default: the beginning, the end, and a step of 1.
text[0]is the first character andtext[-1]is the last.text[2:5]is the characters at positions 2, 3, and 4.text[:3]is the first three characters andtext[3:]is everything from position 3 on.text[::2]takes every second character.text[::-1]reverses the string.- An index that is out of range raises an
IndexError, but a slice that goes past the end is simply shortened.
Try It: Indexing and Slicing
Click Test My Code. Count the positions on paper to check each result, then try your own slices.
text = "Python Programming"
print(text[0], text[-1], text[7])
print(text[0:6])
print(text[7:])
print(text[:6])
print(text[::2])
print(text[::-1])text[0] is P, text[-1] is the last character g, and text[7] is the first letter after the space, P. The output is P g P.text[0:6] takes positions 0 to 5, which gives Python.text[7:] starts at position 7 and continues to the end, which gives Programming.text[:6] starts at the beginning and stops before position 6, which gives Python again.text[::2] takes the characters at positions 0, 2, 4, and so on, which gives Pto rgamn.-1 walks backwards through the whole string, so the output is gnimmargorP nohtyP.Useful String Methods
A method is a function that belongs to an object and is called with a dot, as in text.upper(). Because strings are immutable, a string method never changes the original. It returns a new string, which you must store or print. The most useful methods are:
- Case:
upper(),lower(),title(),capitalize(), andswapcase(). - Cleaning:
strip()removes whitespace from both ends.lstrip()andrstrip()remove it from one end only. - Replacing:
replace(old, new)swaps every occurrence of a piece of text for another. - Searching:
find()returns the position of the first match, or-1if there is none.count()counts matches.startswith()andendswith()test the beginning and the end. - Testing:
isalpha(),isdigit(),isalnum(),isspace(),isupper(), andislower()returnTrueorFalse. - Splitting and joining:
split()breaks a string into a list andjoin()builds a string from a list.
Try It: Cleaning, Changing and Searching
Click Test My Code. Notice that s itself is never changed. Each method call returns a new value.
find() and count() to search.s = " Hello, World "
print(s.strip())
print(s.strip().upper(), s.strip().lower())
print(s.strip().title())
print(s.replace("World", "Python").strip())
print(s.strip().startswith("Hello"), s.strip().endswith("?"))
print(s.find("World"), s.find("xyz"), s.count("l"))s holds two spaces, the text Hello, World, and two more spaces.strip() removes whitespace from both ends. The output is Hello, World.HELLO, WORLD hello, world.title() capitalizes the first letter of every word. The output is Hello, World.replace("World", "Python") returns a new string with the word swapped, and strip() then removes the outer spaces. The output is Hello, Python.Hello, so the first result is True. It does not end with a question mark, so the second result is False. The output is True False.find("World") returns 9, because the original string has two leading spaces. find("xyz") returns -1, which means not found. count("l") counts three letter l characters. The output is 9 -1 3.Splitting and Joining
The split() method cuts a string into a list of smaller strings. With no argument it splits at any run of whitespace, which is ideal for separating words. With an argument, such as split(","), it splits at that exact text. The join() method does the opposite. You call it on the separator and pass the list: "-".join(words). Joining is the fastest and cleanest way to build a long string from many pieces.
Try It: split() and join()
Click Test My Code. The fourth line applies str.capitalize to every word with map() before joining them.
sentence = "the quick brown fox"
words = sentence.split()
print(words)
print(len(words))
print("-".join(words))
print(" ".join(map(str.capitalize, words)))
csv = "red,green,blue"
print(csv.split(","))sentence refers to a string of four words separated by spaces.split() with no argument cuts the string at each space and returns a list of four strings.['the', 'quick', 'brown', 'fox'].len(words) is the number of items in the list. The output is 4.join() is called. The output is the-quick-brown-fox.map(str.capitalize, words) applies the method to every word, and " ".join(...) joins the results with spaces. The output is The Quick Brown Fox.csv refers to three values separated by commas.split(",") cuts the string at each comma. The output is ['red', 'green', 'blue'].Strings Are Immutable
You cannot change a single character of a string. The statement word[0] = "P" raises a TypeError. To get a modified version, build a new string with a method, a slice, or concatenation. Because every method returns a new string, forgetting to store the result is a very common mistake: text.upper() on a line of its own does nothing useful.
You can also compare strings with ==, <, and >. Python compares them character by character using their Unicode code numbers, which you can see with ord(). The reverse function is chr(). Uppercase letters have smaller code numbers than lowercase letters, so "Z" < "a" is True.
Try It: Tests, Immutability and Character Codes
Click Test My Code. Compare the printed values of word and its changed copies.
isalpha() and isdigit(). It shows that capitalize() returns a new string and leaves the original alone, builds a changed copy with replace(), compares strings, and converts between characters and code numbers.word = "python"
print(word.isalpha(), word.isdigit(), "2026".isdigit())
print(word.capitalize(), word)
new_word = word.replace("p", "P")
print(new_word)
print("a" < "b", "Z" < "a")
print(ord("A"), chr(97))word refers to the lowercase string "python".word.isalpha() is True because every character is a letter. word.isdigit() is False. "2026".isdigit() is True. The output is True False True.capitalize() returns Python, but word itself is unchanged. The output is Python python.replace("p", "P") returns a new string and stores it in new_word.Python."a" < "b" is True. "Z" < "a" is also True, because the code number of Z is 90 and that of a is 97. The output is True True.ord("A") returns the code number 65, and chr(97) returns the character a. The output is 65 a.String Formatting
Formatting means building a string from a template and some values. Python has three styles, and you will meet all of them. F-strings are the modern and recommended style. They start with f and evaluate any expression inside curly braces. Beyond simple variables, they support several useful features:
- Expressions:
{items * 4},{name.upper()}, and{len(name)}are evaluated on the spot. - Format specifications:
{score:.1f}shows one decimal place, and{name:^12}centers the text in 12 characters. - The
!rconversion:{name!r}shows the value with quotation marks, exactly as Python would write it. - Self-documenting output:
{score = }prints the expression and its value, which is excellent for debugging (Python 3.8 and later). - Nested fields: a width can come from a variable, as in
{name:^{width}}.
The older str.format() method uses {} placeholders, and the oldest style uses the % operator with codes such as %s and %d. Both are explained in the Input & Output lesson. For new code, prefer f-strings.
Try It: Advanced f-strings
Click Test My Code. Change items to 1 and notice how the word item loses its plural.
!r, picks a singular or plural word with a conditional expression, prints an expression together with its value, runs calculations and method calls inside the braces, and centers a name in a field whose width comes from a variable.name = "Asha"
score = 92.456
items = 3
print(f"{name} scored {score:.1f}")
print(f"{name!r} has {items} item{'s' if items != 1 else ''}")
print(f"{score = }")
print(f"{items * 4} {name.upper()} {len(name)}")
width = 12
print(f"[{name:^{width}}]")name refers to the string "Asha".score refers to the float 92.456.items refers to the integer 3.:.1f shows one digit after the decimal point. The output is Asha scored 92.5.!r displays the string with its quotation marks. The expression 's' if items != 1 else '' adds an s unless there is exactly one item. The output is 'Asha' has 3 items.{score = } prints the text score = followed by the value. The output is score = 92.456.items * 4, calls name.upper(), and calls len(name). The output is 12 ASHA 4.width refers to 12.{width} is filled in first, so the format becomes ^12. The name is centered in 12 characters, and the output is [ Asha ].Working with Text from the User
Combining input with string methods lets you analyze text that a user types. Remember that input() returns a string, so all the string methods are available on it immediately. A for loop can walk through a string one character at a time, and the in operator checks whether a character or a piece of text appears in another string.
Try It: A Text Analyzer
The Program Input box is already filled with the sentence Python is fun. Click Run Code straight away, then type another sentence in the box and run it again.
text = input("Enter a sentence: ")
words = text.split()
print("Characters:", len(text))
print("Words:", len(words))
print("Uppercase:", text.upper())
print("Reversed:", text[::-1])
vowels = 0
for ch in text.lower():
if ch in "aeiou":
vowels += 1
print("Vowels:", vowels)input() reads the first line of the Program Input box and stores it as a string in text.split() cuts the sentence at the spaces and returns a list of the words.len(text) counts every character, including the spaces. For Python is fun the output is Characters: 13.len(words) counts the items in the list. The output is Words: 3.Uppercase: PYTHON IS FUN.[::-1] reverses the string. The output is Reversed: nuf si nohtyP.vowels = 0 creates a counter that starts at zero.for loop visits each character of the lowercase text one at a time and stores it in ch. Lowercasing first means that capital vowels are counted too.ch in "aeiou" is true when the character appears in the string of vowels.if block inside the for loop.o, i, and u, so the output is Vowels: 3.Try It: A Palindrome Checker
A palindrome reads the same forwards and backwards. The Program Input box is filled with Never odd or even. Click Run Code, then try a word such as Python.
word = input("Enter a word: ").strip().lower()
cleaned = word.replace(" ", "")
if cleaned == cleaned[::-1]:
print(f"'{word}' is a palindrome")
else:
print(f"'{word}' is not a palindrome")input() reads the text, strip() removes outer whitespace, and lower() makes every letter lowercase, so word holds never odd or even.replace(" ", "") deletes every space, which gives neveroddoreven.cleaned[::-1] is the reversed string. If it equals the original, the text is a palindrome. For this phrase the comparison is True.'never odd or even' is a palindrome.else: handles every other case.python.Tip: To build a long string from many pieces, collect the pieces in a list and call "".join(pieces) once at the end. It is faster and cleaner than adding to a string in a loop.
Common Mistakes with Strings
- Forgetting to store the result:
text.upper()on its own changes nothing. Writetext = text.upper(). - Assigning to a character:
word[0] = "J"raises aTypeError, because strings are immutable. Build a new string instead. - IndexError:
"abc"[3]fails because the valid indexes are 0, 1, and 2. Slices are forgiving, but single indexes are not. - Off-by-one slices: the stop position is not included, so
text[0:5]has 5 characters, positions 0 to 4. - Joining text and numbers with +:
"Age: " + 21raises aTypeError. Use an f-string orstr(). - Calling join on the list:
words.join("-")fails. The separator owns the method:"-".join(words). - Mismatched quotes: a string that begins with
"must end with". Switch the quote type or escape the inner quote.
Key Takeaways
- A string is an immutable sequence of Unicode characters, written with single, double, or triple quotes.
- Indexes start at 0, negative indexes count from the end, and slices use
[start:stop:step]with the stop position excluded. - String methods return new strings, so store the result of
upper(),strip(),replace(), and the others. split()turns a string into a list, and"sep".join(list)turns a list back into a string.find(),count(),startswith(),endswith(), andinsearch inside strings.- F-strings are the preferred way to format text and support expressions, widths, alignment,
!r, and=. - Strings compare by Unicode code number, so uppercase letters sort before lowercase ones.
Frequently Asked Questions
How do I create a string in Python?
Write text inside single quotes, double quotes, or triple quotes, for example name = “Asha”. Single and double quotes mean the same thing. Triple quotes create a string that can span several lines and keeps the line breaks.
What is string slicing in Python?
Slicing takes a part of a string with the syntax text[start:stop:step]. The slice includes the start position and stops before the stop position. For example, “Python”[0:3] gives “Pyt”, and text[::-1] reverses a string.
Are Python strings mutable?
No. Strings are immutable, so you cannot change a character in place, and word[0] = “J” raises a TypeError. String methods such as upper() or replace() return a new string and leave the original unchanged.
How do I reverse a string in Python?
Use slicing with a step of -1, for example reversed_text = text[::-1]. This walks through the whole string backwards and returns a new string. The original string is not modified.
How do I remove whitespace from a string in Python?
Use strip() to remove whitespace from both ends of a string, lstrip() to remove it only from the left end, and rstrip() to remove it only from the right end. To remove spaces inside a string, use replace(” “, “”).
How do I join a list of strings into one string in Python?
Call join() on the separator and pass the list, for example “-“.join([“a”, “b”, “c”]) gives “a-b-c”. Every item in the list must be a string. To go the other way, use split().
How do I check if a string contains a substring in Python?
Use the in operator, for example “th” in “Python” returns True. You can also use find(), which returns the position of the first match or -1 if there is none, and startswith() or endswith() to test the beginning or the end.
What is the best way to format strings in Python?
F-strings are the recommended way. Put an f before the opening quote and write expressions inside curly braces, for example f”{name} scored {score:.1f}”. They are shorter and more readable than str.format() or the % operator, and they support widths, alignment, and number formats.