A Python string stores text as an ordered sequence of characters. You can read characters by index, slice parts of the text, and create new strings with methods.
Strings are immutable, so methods such as strip(), replace(), lower(), and title() return a new string instead of changing the old one in place.
Most string bugs come from assuming a separator, index, or length exists. Check the input shape before slicing, splitting, or converting text.
A string is a sequence of characters enclosed in single, double, or triple quotes. Strings are immutable - once created, they cannot be changed in place.
single = 'single quotes'
double = "double quotes"
multiline = """A string can span
multiple lines."""
tab = "Hello\tWorld"
newline = "Line 1\nLine 2"
quote = "She said \"hi\""
backslash = "C:\\Users\\Alice"
path = r"C:\Users\Alice\Documents"
pattern = r"\d+\.\d+"
print(len("Python"))
print(type("hello"))
s = "Python"
# P y t h o n
# 0 1 2 3 4 5 (positive index)
# -6-5-4-3-2-1 (negative index)
print(s[0]) # P
print(s[-1]) # n
print(s[2]) # t
# Slicing: s[start:stop:step]
print(s[1:4]) # yth
print(s[:3]) # Pyt
print(s[3:]) # hon
print(s[::2]) # Pto (every 2nd char)
print(s[::-1]) # nohtyP (reversed)
# Strings are immutable
# s[0] = "J" # TypeError!
# Create a new string instead:
new_s = "J" + s[1:]
print(new_s) # Jython
name = "Alice"
age = 25
pi = 3.14159
# f-strings (Python 3.6+) - recommended
print(f"Hello, {name}! You are {age} years old.")
print(f"Pi = {pi:.2f}") # 2 decimal places
print(f"{age:05d}") # 00025 (zero-padded)
print(f"{'left':<10}|") # left-aligned
print(f"{'right':>10}|") # right-aligned
print(f"{'center':^10}|") # centered
print(f"{1_000_000:,}") # 1,000,000 (thousands separator)
# format() method
print("Hello, {}! Age: {}".format(name, age))
print("Hello, {name}!".format(name="Bob"))
# % formatting (old style)
print("Hello, %s! Age: %d" % (name, age))
print("Pi = %.2f" % pi)
# Multiline f-string
report = (
f"Name: {name}\n"
f"Age: {age}\n"
f"Pi: {pi:.4f}"
)
print(report)
| Method | Description | Example |
|---|---|---|
| upper() | Uppercase | "hi".upper() -> "HI" |
| lower() | Lowercase | "HI".lower() -> "hi" |
| title() | Title case | "hello world".title() -> "Hello World" |
| strip() | Remove leading/trailing whitespace | " hi ".strip() -> "hi" |
| lstrip() / rstrip() | Strip left or right only | |
| replace(old, new) | Replace substring | "abc".replace("b","x") -> "axc" |
| split(sep) | Split into list | "a,b,c".split(",") -> ['a','b','c'] |
| join(iterable) | Join list into string | ",".join(["a","b"]) -> "a,b" |
| find(sub) | Index of first occurrence (-1 if not found) | "hello".find("l") -> 2 |
| index(sub) | Like find but raises ValueError | |
| count(sub) | Count occurrences | "hello".count("l") -> 2 |
| startswith(s) | Check prefix | "hello".startswith("he") -> True |
| endswith(s) | Check suffix | "hello".endswith("lo") -> True |
| isdigit() | All digits- | "123".isdigit() -> True |
| isalpha() | All letters- | "abc".isalpha() -> True |
| isalnum() | Letters or digits- | |
| zfill(n) | Zero-pad to width n | "42".zfill(5) -> "00042" |
| center(n) | Center in width n | "hi".center(10) |
text = " Hello, World! "
print(text.strip()) # "Hello, World!"
print(text.lower()) # " hello, world! "
print(text.upper()) # " HELLO, WORLD! "
print(text.replace("World", "Python")) # " Hello, Python! "
csv = "apple,banana,cherry"
fruits = csv.split(",")
print(fruits) # ['apple', 'banana', 'cherry']
print(" | ".join(fruits)) # apple | banana | cherry
sentence = "the quick brown fox"
print(sentence.title()) # The Quick Brown Fox
print(sentence.count("the")) # 1
print(sentence.find("quick")) # 4
print(sentence.startswith("the")) # True
# Method chaining
clean = " HELLO WORLD ".strip().lower().replace(" ", "_")
print(clean) # hello_world
first = "Hello"
last = "World"
print(first + ", " + last + "!")
print("ha" * 3)
print("ell" in "Hello")
chars = list("Python")
print(chars)
template = """Dear {name},
Your order #{order_id} has shipped.
Expected delivery: {date}
"""
print(template.format(name="Alice", order_id=12345, date="June 20"))
Real text often contains extra spaces, missing separators, unexpected casing, or empty values. Clean the text first, then split or convert it.
When split() is used for structured input, check how many parts came back. If the separator may be missing, partition() can be safer because it always returns three values.
When slicing, remember that a missing index can still return an empty string rather than an error. Print repr(value) while debugging so spaces and blank strings are visible.
0 of 2 checked
Try this next
0 of 3 completed
Strings are immutable. Methods such as replace and strip return a new string, so assign the result if you need to keep it.
It returns a one-item list containing the original string. Code expecting two parts should check the length or use partition.
Use find when a missing substring is expected and -1 is convenient. index raises ValueError when no match exists.
Explore 500+ free tutorials across 20+ languages and frameworks.