Strings are how Python represents text — anything wrapped in single quotes, double quotes, or triple quotes. They're one of the most-used data types in any program, and Python gives them a large set of built-in methods for searching, transforming, and reformatting text without needing any extra libraries.
The single most important fact about Python strings: they're immutable. Once created, a string's characters can never be changed in place — every "modification" you make actually creates and returns a brand new string.
Creating and Concatenating Strings
name = "Alice"
greeting = 'Hello'
# concatenation with +
message = greeting + ", " + name + "!"
print(message)
# repetition with *
print("-" * 10)
Output:
Hello, Alice!
----------
For anything beyond simple concatenation — especially mixing in variables and numbers — f-strings are the cleaner, more modern approach.
Common String Methods
Because strings are immutable, every method below returns a new string rather than changing the original.
text = " Hello, World! "
print(text.strip()) # remove leading/trailing whitespace
print(text.upper()) # " HELLO, WORLD! "
print(text.lower()) # " hello, world! "
print(text.strip().replace("World", "Python"))
print(text.strip().split(", ")) # splits into a list
Output:
Hello, World!
HELLO, WORLD!
hello, world!
Hello, Python!
['Hello', 'World!']
.join() is the reverse of .split() — it combines a list of strings back into one, using the string it's called on as the separator:
words = ["Python", "is", "fun"]
sentence = " ".join(words)
print(sentence)
Output:
Python is fun
Why Immutability Matters
Because strings can't be changed in place, trying to modify a single character directly raises an error:
word = "cat"
word[0] = "b" # TypeError: 'str' object does not support item assignment
To "change" a character, you build an entirely new string instead — often with slicing (covered in String Slicing) or one of the methods above. You can see string manipulation in a full worked example in reversing a string, which relies on this same slicing behavior.
