Skip to content

Python Strings

Master Python strings: slicing, methods, f-strings, formatting, and encoding for text processing.

What you'll learn

  • Create and slice strings with indexing
  • Use essential string methods (split, join, replace, strip)
  • Format strings with f-strings and format()
  • Check and search strings with in, startswith, find
  • Handle multi-line and raw strings

Concept

Creating Strings

Strings in Python are immutable sequences of Unicode characters. You create them with single, double, or triple quotes:

single = 'hello'
double = "world"
multi = """This is a
multi-line string"""
raw = r"C:\path\no\escape"

Triple quotes are ideal for docstrings and multi-line text. Raw strings (prefixed with r) treat backslashes literally — essential for Windows paths and regex patterns.

Indexing and Slicing

You access characters by index and extract substrings with slicing [start:stop:step]:

text = "Python"
print(text[0])     # P  (first char)
print(text[-1])    # n  (last char)
print(text[0:3])   # Pyt (chars 0,1,2)
print(text[2:])    # thon (from index 2 to end)
print(text[::-1])  # nohtyP (reversed!)

Negative indices count from the end. The slice [::-1] is the idiomatic way to reverse a string. Slicing never raises an IndexError — it just returns what is available.

Essential String Methods

Python strings come with dozens of built-in methods. The most used ones:

  • .split() — break a string into a list of substrings
  • .join() — combine a list of strings with a separator
  • .replace() — replace all occurrences of a substring
  • .strip() — remove leading/trailing whitespace
  • .upper() / .lower() — change case
  • .startswith() / .endswith() — check prefixes/suffixes
  • .find() — return the index of a substring, or -1
csv_line = "Ada,25,admin"
parts = csv_line.split(",")        # ['Ada', '25', 'admin']
joined = "-".join(parts)           # Ada-25-admin
clean = "  hello  ".strip()        # hello

F-Strings (Formatted String Literals)

Introduced in Python 3.6, f-strings are the fastest and most readable way to embed expressions in strings:

name = "Ada"
age = 25
print(f"{name} is {age} years old")
print(f"Next year: {age + 1}")
print(f"{name:>10}")    # right-align in 10 chars
print(f"{3.14159:.2f}") # 3.14 (2 decimal places)

F-strings support format specifiers for alignment, width, precision, and more. They are preferred over the older % formatting and .format() method.

Searching and Checking

text = "Hello, Python!"
print("Python" in text)          # True
print(text.startswith("Hello"))  # True
print(text.find("Python"))       # 7 (index)
print(text.find("Java"))         # -1 (not found)

Use the in operator for membership tests — it is clearer than .find() != -1. Because strings are immutable, every "modification" method returns a new string; the original is never changed in place.

Example

              # Creating strings
single = 'hello'
double = "world"
multi = """Multi-line
string here"""
raw = r"C:\users\ada"  # backslashes are literal

# Indexing and slicing
text = "Python"
print(text[0])      # P
print(text[-1])     # n
print(text[0:3])    # Pyt
print(text[::-1])   # nohtyP (reversed)

# Essential methods
csv_line = "Ada,25,admin"
parts = csv_line.split(",")
print(parts)                    # ['Ada', '25', 'admin']
print("-".join(parts))          # Ada-25-admin
print("  hello  ".strip())      # hello
print("hello".replace("l", "L"))  # heLLo

# F-strings
name = "Ada"
age = 25
print(f"{name} is {age} years old")
print(f"{3.14159:.2f}")         # 3.14
print(f"{name:>10}")            # right-aligned

# Searching
sentence = "Hello, Python!"
print("Python" in sentence)     # True
print(sentence.startswith("H")) # True
print(sentence.find("Java"))    # -1
            

Demonstrates string creation, slicing (including reverse), key methods (split, join, strip, replace), f-string formatting with specifiers, and membership testing with in and find.

Try it

  • Text Counter

    Count characters, words, and lines — classic string operations.

  • Case Converter

    Convert between snake_case, camelCase, etc. using string methods.

Common mistakes

The mistake

Trying to modify a string in place like text[0] = 'p'

The fix

Strings are immutable. Use text = text.replace('P', 'p') or text = 'p' + text[1:] to create a new string. This is the most common beginner surprise with strings.

The mistake

Confusing find() returning -1 with a valid index

The fix

find() returns -1 when the substring is not found, which is a valid index from the end. Use the 'in' operator for membership tests, or use .index() which raises ValueError if not found.

Related Cheatsheets

Practice Python Strings

18 exercises

Practice Python Strings

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Build real projects

Apply what you learned by building guided projects with starter code and solutions.

View projects

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors