Python Strings: The Complete Guide with Examples
Part 3 of the Python for Everyone track. Last updated: September 2026.
Strings are immutable sequences of characters — you cannot change one in place, but Python gives you a rich set of methods to build new ones. Master slicing and f-strings and 90% of string work becomes trivial.
Creating strings
s1 = "double quotes" s2 = 'single quotes' # identical to double quotes s3 = """triple quotes span multiple lines""" raw = r"C:\new\folder" # raw string — backslashes not treated as escapes
Indexing and slicing
s = "Python" print(s[0]) # P (first character) print(s[-1]) # n (last character — negative index counts from end) print(s[0:3]) # Pyt (start:stop — stop is EXCLUDED) print(s[:3]) # Pyt print(s[2:]) # thon print(s[::-1]) # nohtyP (reverse!)
The slice pattern is s[start:stop:step]. Remember: stop is excluded, and negative step reverses.
Essential string methods
text = " Hello, World! "
print(text.strip()) # "Hello, World!" — remove surrounding whitespace
print(text.lower()) # " hello, world! "
print(text.upper()) # " HELLO, WORLD! "
print(text.replace("World", "Python")) # " Hello, Python! "
csv = "a,b,c"
print(csv.split(",")) # ['a', 'b', 'c']
print("-".join(["a", "b", "c"])) # "a-b-c" (join is called ON the separator)
print("python".startswith("py")) # True
print("python".endswith("on")) # True
print("hello world".find("world"))# 6 (-1 if not found)
print("banana".count("a")) # 3
join() is the fast, idiomatic way to build strings from lists — never concatenate in a loop.
Immutability: what it means in practice
s = "hello" # s[0] = "H" # TypeError! strings cannot be changed in place s = "H" + s[1:] # build a NEW string instead → "Hello"
Formatting recap
name, n = "Ada", 3
print(f"{name} has {n} laptops") # f-string (preferred)
print("{} has {} laptops".format(name, n)) # older style — still seen in legacy code
Common gotchas
- strip() removes characters from both ends only, not the middle.
- find() returns -1 when missing; index() raises an error instead.
- String methods return new strings — text.upper() alone changes nothing unless you assign it.
Key takeaways
- Slice with s[start:stop:step]; stop excluded; [::-1] reverses.
- split() / join() convert between strings and lists.
- Strings are immutable — methods return new strings.
- f-strings for formatting, always.
Next in this series: Python Lists, Tuples, Sets and Dictionaries Explained.
Comments
Post a Comment