Python str is immutable Unicode text. Concatenation uses +, but f-strings (f"...") are the idiomatic way to embed expressions—cleaner than % formatting or .format().
f-strings and literals
name = "Ada"
msg = f"Hello, {name}!"
path = r"C:\logs\app.txt" # raw string: backslashes literal
multiline = """line one
line two"""
Common string methods
"hello".upper()
" trim ".strip()
"a,b,c".split(",")
",".join(["a", "b", "c"])
Strings are immutable—methods return new strings. For heavy building, use io.StringIO or join lists of parts.
Important interview questions and answers
- Q: Why are strings immutable?
A: Hash stability for dict keys, thread-safe sharing, and predictable behavior—like Java strings. - Q: f-string vs + concatenation?
A: f-strings are readable and efficient; repeated+in loops allocates many interim strings.
Self-check
- What prefix creates a raw string?
- Does
upper()mutate the original string?
Tip: Prefer f-strings over + in loops—strings are immutable and repeated concat allocates interim objects.
Interview prep
- f-string vs format?
Both work; f-strings embed expressions inline and are the modern default for readability.
- Immutable strings?
Methods like
upper()return new strings—original unchanged, enabling safe dict keys and hashing.