String Manipulation & Formatting
Text is everywhere in programming. Learn how to slice, dice, modify, and beautifully format strings in Python.
Strings as Sequences
In Python, a string is just a sequence of characters. Because it's a sequence, you can extract individual characters using their position (index), starting from 0.
word = "Python"
print(word[0]) # Prints 'P'
print(word[-1]) # Prints 'n' (negative index counts from the end)Slicing Strings
You can carve out chunks of a string using the slicing syntax: [start:stop:step].
text = "Hello World"
print(text[0:5]) # Prints 'Hello'
print(text[::-1]) # A neat trick to reverse a string!Essential String Methods
Strings come with built-in superpowers (methods) that let you modify them on the fly:
text.upper()/text.lower(): Changes casing.text.strip(): Removes accidental whitespace from the start and end.text.replace("old", "new"): Swaps out words or characters.text.split(","): Chops the string into a list based on a separator.
F-Strings: The Modern Way to Format
Formatting text used to be messy. Python 3.6 introduced f-strings, which let you inject variables directly into strings by wrapping them in curly braces.
name = "Sarah"
score = 95
print(f"Great job {name}, you scored {score} points!")