Course topics

By WebNest Studio Engineering Team

Python Tutorial

Python Strings

Strings are one of the most frequently used data types in Python, representing sequences of text characters. Python strings are immutable, meaning that once created, a string's characters cannot be changed in place — any operation that appears to "modify" a string actually creates and returns a brand-new string.

Python offers rich, readable tools for building and manipulating text, from the modern f-string syntax for embedding expressions directly into text, to a large set of built-in string methods for searching, splitting, joining, and cleaning up text data.

Why it matters

Names, messages, file contents, web pages and API responses are all text, so string handling is in every program. Slicing, splitting and joining are the operations used most, and because strings cannot be changed in place, knowing that each operation returns a new string prevents a very common mistake.

f-strings

Formatted string literals, or f-strings, are written by placing an "f" before the opening quote, and they let you embed any expression directly inside curly braces: f"Hello, {name}! You are {age} years old.". The expression inside the braces is evaluated at runtime and converted to its string form automatically, and f-strings also support format specifiers for things like decimal precision, e.g. f"{price:.2f}".

Indexing and Slicing Strings

Since a string is an ordered sequence of characters, it supports the same indexing and slicing rules as a list: text[0] gets the first character, text[-1] gets the last, and text[2:5] extracts a substring from index 2 up to (but not including) index 5. Because strings are immutable, slicing always returns a new string rather than a view into the original.

Common String Methods

Python strings come with many useful built-in methods, all of which return a new string or value rather than modifying the original.

  • split(sep) — breaks a string into a list of substrings using sep as the delimiter (whitespace by default).
  • join(iterable) — the reverse of split; joins the elements of an iterable of strings using the original string as the separator, e.g. ", ".join(["a", "b", "c"]).
  • strip() — removes leading and trailing whitespace (or specified characters) from a string; lstrip() and rstrip() trim only one side.
  • format() — an older but still-used way to embed values into a string, e.g. "{} is {} years old".format(name, age).
  • upper(), lower(), replace(old, new), and startswith()/endswith() round out the most commonly used methods.

Examples

f-strings, indexing, and slicing

Python
name = "Priya"
age = 29
price = 49.5

print(f"Hello, {name}! You are {age} years old.")
print(f"Price: {price:.2f}")

text = "Programming"
print(text[0], text[-1])
print(text[3:7])
print(text[::-1])
Output
Hello, Priya! You are 29 years old.
Price: 49.50
P g
gram
gnimmargorP

split, join, and strip in action

Python
sentence = "  the quick brown fox  "
cleaned = sentence.strip()
print(f"'{cleaned}'")

words = cleaned.split()
print(words)

joined = "-".join(words)
print(joined)

print("Python".upper())
print("Python".replace("y", "Y"))
Output
'the quick brown fox'
['the', 'quick', 'brown', 'fox']
the-quick-brown-fox
PYTHON
PYthon

Common Mistakes

  • Trying to modify a string in place, such as text[0] = "P", forgetting that strings are immutable and this raises a TypeError.
  • Calling a string method and forgetting to capture its return value, since methods like strip() and replace() return a new string rather than changing the original.
  • Forgetting that slicing's stop index is exclusive, leading to off-by-one substrings.
  • Mixing up split() (string to list) and join() (list to string), or calling join() on the list instead of on the separator string.

Exercise

Starting from the text below, print the number of words it contains, then the word Python reversed, then the words joined with hyphens.

Expected output: 3, nohtyP, Hello,-Python-World (one per line)

Python · starter code
text = "  Hello, Python World  "

# TODO: split the text into words and print how many there are
# TODO: print the second word reversed
# TODO: print the words joined with "-"
Show hints
  • text.split() with no argument splits on any whitespace and ignores the spaces at the ends.
  • The slice [::-1] gives a reversed copy, and "-".join(words) joins a list of strings.
Show solution
Python · solution
text = "  Hello, Python World  "

words = text.split()
print(len(words))
print(words[1][::-1])
print("-".join(words))

Quick quiz

1. What happens when you run s = "cat" and then s[0] = "b"?

  • A. s becomes "bat"
  • B. s becomes "b"
  • C. TypeError is raised, because strings are immutable
  • D. Nothing happens
Show answer

C. A string cannot be changed in place. Build a new one, for example "b" + s[1:].

2. What is the value of "python"[-1]?

  • A. p
  • B. n
  • C. o
  • D. It raises an error
Show answer

B. Negative indexes count from the end, so -1 is the last character.

3. What is the value of "python"[1:4]?

  • A. pyt
  • B. ytho
  • C. yth
  • D. pyth
Show answer

C. A slice includes the start index and stops before the end index: positions 1, 2 and 3.

Interview questions

How do you reverse a string in Python?

Show answer

Use a slice with a step of -1: text[::-1]. It returns a new string with the characters in reverse order. "".join(reversed(text)) does the same. There is no reverse() method on strings, because they are immutable.

Why is join() preferred to + for building a string in a loop?

Show answer

Strings are immutable, so each + creates a new string and copies everything built so far; doing this repeatedly in a loop becomes slow for many pieces. Collecting the pieces in a list and calling "".join(pieces) once builds the result in a single pass.

Key Points to Remember

  • Python strings are immutable; every "modifying" operation returns a new string.
  • f-strings (f"...{expr}...") are the modern, readable way to embed expressions and formatting into text.
  • Strings support indexing and slicing just like lists, since they are ordered sequences of characters.
  • split(), join(), strip(), and format() are among the most commonly used string methods for real-world text processing.

Practice in the playground

Write and run your own code for this topic, or start from the exercise or an example. Runs Python in your browser. Your code for each topic is kept in this browser.

Run the examples

Change an input, predict the result, then compare it with the output. Explain why the result changes.

WebNest Studio

Written by

WebNest Studio Engineering Team

Practical lessons from developers working with Java, Python, React, databases and production systems.

Led by Vansh Duggal, Founder, WebNest Studio · Full-stack & software engineering