Python Tutorial 0/52 lessons ~6 min read Lesson 21
Strings
Python strings are immutable Unicode sequences.
Course progress0%
Focus
9 guided sections
Practice signal
Examples included
Career prep
Interview Q&A included
Introduction
Python strings are immutable Unicode sequences. Rich method API: split, join, strip, replace, format, f-strings.
Understanding the topic
Core concepts to understand:
- Immutable — every 'edit' creates a new string.
- f-strings (3.6+) are the modern format.
joinover+=in loops.strvsbytes— Unicode vs raw octets.
Syntax reference
Visual flow / code:
python
name = "Alice"greeting = f"Hello, {name.upper()}!"# Split / joinparts = "a,b,c".split(",") # ['a','b','c']joined = "-".join(parts) # 'a-b-c'# Strip & replace" hi ".strip()"hello".replace("l", "L")# Multi-line + f-string with format specpi = 3.14159print(f"pi = {pi:.2f}")# Encode/decodeb = "café".encode("utf-8")s = b.decode("utf-8")
Execution workflow
1Strings Workflow
1 / 4Immutable
every 'edit' creates a new string.
Real-world use
Use f-strings everywhere. Use str.join for building large strings — it's O(n), while += in a loop is O(n²).
Best practices
- Prefer f-strings (fastest, clearest).
- Use
joinfor concatenating many parts. - Always specify encoding for bytes ↔ str.
Common mistakes
s += '...'in a loop builds quadratic-time garbage.
Advanced interview questions
Interview Prep
Practice concise answers, then expand each card for the explanation.
1BeginnerQuestionWhy are strings immutable?+
Answer
Strings are immutable so they can be safely shared, cached, and used as dict keys because their hash never changes. It also lets CPython intern some strings and avoid defensive copying. The downside is that operations like repeated
+= create new strings, so use ''.join(...) to build large strings.Follow-up
Why is join preferred over repeated concatenation?
2IntermediateQuestionf-string vs % vs format?+
Answer
F-strings (3.6+) evaluate expressions inline and are generally the most readable and fastest.
str.format uses positional or named placeholders and is useful when the template is stored separately. The % operator is the older printf-style and remains supported, but f-strings are preferred for new code, while logging often still uses lazy %s formatting.Follow-up
Why does the logging module prefer %-style arguments?
3IntermediateQuestionstr vs bytes?+
Answer
str is a sequence of Unicode code points for text, while bytes is an immutable sequence of integers from 0 to 255 for raw binary data. You convert between them with str.encode(encoding) and bytes.decode(encoding), usually using UTF-8. Mixing them raises TypeError, so decode at input boundaries and encode at output.Follow-up
What happens if you decode bytes with the wrong encoding?
Summary
In summary: Immutable Unicode. f-strings + join = idiomatic.
Ready to mark this lesson complete?Track your journey across the entire course.