Strings
Checking access...
Strings are sequences of characters. Python treats strings as first-class objects with rich functionality.
Creating Strings
# Single or double quotes — both worksingle = 'Hello'double = "World"
# Triple quotes for multilinemultiline = """This is amultiline string"""
# No char type — single chars are strings of length 1letter = "A"print(len(letter)) # 1String Indexing and Slicing
text = "Python"
# Indexing — 0-basedtext[0] # 'P'text[-1] # 'n' — negative indexes from the end
# Slicing — [start:stop:step]text[0:3] # 'Pyt' — indexes 0, 1, 2text[:3] # 'Pyt' — start defaults to 0text[3:] # 'hon' — stop defaults to endtext[::2] # 'Pto' — every 2nd charactertext[::-1] # 'nohtyP' — reverseF-Strings (Python 3.6+)
The modern way to format strings:
name = "Alice"age = 25
# Basic f-stringprint(f"{name} is {age} years old")# Alice is 25 years old
# Expressions insideprint(f"Next year, {name} will be {age + 1}")
# Formatting numberspi = 3.14159print(f"Pi to 2 decimals: {pi:.2f}") # 3.14print(f"Percentage: {0.25:.1%}") # 25.0%
# Padding and alignmentprint(f"|{'left':<10}|") # |left |print(f"|{'right':>10}|") # | right|print(f"|{'center':^10}|") # | center |Tip
F-strings are preferred over .format() and % formatting for readability and performance.
Common String Methods
text = " Hello, Python World! "
# Case manipulationtext.upper() # ' HELLO, PYTHON WORLD! 'text.lower() # ' hello, python world! 'text.title() # ' Hello, Python World! 'text.swapcase() # ' hELLO, pYTHON wORLD! '
# Searchingtext.find("Python") # 9 — index of first occurrencetext.find("Java") # -1 — not foundtext.count("o") # 3"Python" in text # True
# Validation"hello".isalpha() # True"123".isdigit() # True"hello123".isalnum() # True" ".isspace() # True
# Manipulationtext.strip() # 'Hello, Python World!' — removes leading/trailing whitespacetext.replace("Python", "Java") # ' Hello, Java World! '"a,b,c".split(",") # ['a', 'b', 'c']"-".join(["a", "b", "c"]) # 'a-b-c'Escape Sequences
# Common escapesprint("Line 1\nLine 2") # newlineprint("Tab\tseparated") # tabprint("Quote: \"") # literal quoteprint("Backslash: \\") # literal backslash
# Raw strings — ignore escapes (great for paths/regex)path = r"C:\Users\name"regex = r"\d+\.\d+"String Immutability
# Strings are immutable — cannot change in placetext = "hello"# text[0] = "H" # TypeError!
# Must create a new stringtext = "H" + text[1:] # 'Hello'Key Takeaways
- Strings use f-strings for formatting —
f"{variable}" - Slicing:
string[start:stop:step]— negative indexes count from the end - Common methods:
.strip(),.split(),.join(),.replace(),.find() - Strings are immutable — operations return new strings
- Use raw strings (
r"...") for paths and regex patterns