Academic Block

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(), and join().
  • 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.

What this code does: It creates one string with single quotes, one with double quotes that contains an apostrophe, and one that spans two lines with triple quotes. It prints the strings and the length of the multi-line one.
single = 'Hello'
double = "It's Python"
multi = """Line one
Line two"""
print(single, double)
print(multi)
print(len(multi))

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 and text[-1] is the last.
  • text[2:5] is the characters at positions 2, 3, and 4.
  • text[:3] is the first three characters and text[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.

What this code does: It stores a phrase and prints single characters by positive and negative index, then prints several slices: a start and stop, an open end, an open start, every second character, and the reversed string.
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])

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(), and swapcase().
  • Cleaning: strip() removes whitespace from both ends. lstrip() and rstrip() 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 -1 if there is none. count() counts matches. startswith() and endswith() test the beginning and the end.
  • Testing: isalpha(), isdigit(), isalnum(), isspace(), isupper(), and islower() return True or False.
  • Splitting and joining: split() breaks a string into a list and join() 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.

What this code does: It starts with a string that has extra spaces around it. It removes the spaces, changes the case in three ways, replaces a word, tests the start and end of the text, and uses 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"))

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.

What this code does: It splits a sentence into words, counts them, joins the words back together with a hyphen and with a space, and splits a comma-separated string into a list.
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(","))

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.

What this code does: It tests a word and a number string with 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))

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 !r conversion: {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.

What this code does: It formats a score to one decimal place, shows a name with !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}}]")

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.

What this code does: It reads a sentence and prints the number of characters, the number of words, the sentence in uppercase, and the sentence reversed. A loop then goes through the lowercase text letter by letter and counts the vowels.
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)

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.

What this code does: It reads a phrase, removes the outer whitespace, and converts it to lowercase. It then removes the spaces, compares the result with its reverse, and prints whether the phrase is a palindrome.
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")
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. Write text = text.upper().
  • Assigning to a character: word[0] = "J" raises a TypeError, 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: " + 21 raises a TypeError. Use an f-string or str().
  • 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(), and in search 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.

Ready for the next step?Learn how to work with numbers and the math functions.
Next: Numbers & Math Functions →