Strings & String Methods

Difficulty: Beginner

Question

Explain how strings work in Python, the most useful string methods, slicing, and f-string formatting.

Answer

A Python str is an immutable sequence of Unicode code points. You can index and slice it like a list, but every "modification" (upper(), replace(), concatenation) returns a new string. Formatting is done best with f-strings, such as f"Total: {amount:,.2f}", which are evaluated at runtime and are the fastest and most readable option in modern Python.

Immutability and what it means for performance

Because strings cannot change, they are hashable (usable as dict keys), safe to share between threads and can be interned by the interpreter. The cost shows up when building strings in a loop: s += piece may create a new string each time, turning an O(n) job into O(n²) in the worst case. CPython sometimes optimises += in place, but do not rely on it. Collect parts in a list and call "".join(parts) once.

Strings are Unicode, so len("नमस्ते") counts code points (6 here), not bytes or visible characters. Converting to bytes for files or the network uses s.encode("utf-8"), and b.decode("utf-8") goes back.

Indexing and slicing

s[start:stop:step] returns a new string; stop is exclusive and out-of-range indices in a slice are clamped rather than raising.

Single-index access out of range (s[100]) raises IndexError; slicing (s[100:]) returns "".

Methods you will actually use

TaskMethod
Clean inputstrip(), lstrip(), rstrip()
Change caselower(), upper(), title(), casefold() for case-insensitive compare
Split and joinsplit(), split(","), rsplit(maxsplit=1), "-".join(items)
Searchin, find() (returns -1), index() (raises), count(), startswith(), endswith()
Replacereplace(old, new, count)
Prefix/suffixremoveprefix(), removesuffix() (Python 3.9+)
Validateisdigit(), isalpha(), isalnum(), isspace()
Padzfill(), ljust(), rjust(), center()

A frequent bug is s.strip("https://"): strip removes any of those characters from both ends, not the prefix. Use removeprefix("https://") instead.

f-strings and formatting

f-strings (Python 3.6+) evaluate expressions inline: f"{name!r}", f"{price:.2f}", f"{count:,}", f"{ratio:.1%}", f"{n:>8}", f"{dt:%d-%m-%Y}". The = specifier (3.8+) is great for debugging: f"{total=}" prints total=1500. Since Python 3.12 (PEP 701), f-strings can reuse the same quote type inside expressions and span lines, so f"{user["name"]}" is valid.

Python 3.14 added template strings (PEP 750): t"Hello {name}" returns a string.templatelib.Template object instead of a str, letting libraries process the static parts and the interpolated values separately, for example to escape HTML or build safe SQL. The older str.format() and % formatting still work and you will see them in legacy code and in logging calls.

Common interview tasks

Reversing a string, checking palindromes (normalise with casefold() and filter isalnum()), counting characters (collections.Counter), checking anagrams (sorted(a) == sorted(b) or comparing Counters) and parsing input like "name,phone,city" with split(",") all come up in online assessments. Know the time complexity: in on a string is O(n·m) in the worst case, join is O(total length).

Code examples

Slicing and common methods

s = "  Hello, InternHack  "
clean = s.strip()
print(clean.lower(), clean[:5], clean[::-1])
print(clean.split(", "))
print("-".join(["2026", "10", "12"]))

url = "https://razorpay.com"
print(url.removeprefix("https://"))     # correct
print("happy.py".strip(".py"))           # strips characters, not suffix
print("hello.py".removesuffix(".py"))

word = "Madam"
print(word.casefold() == word.casefold()[::-1])

strip(chars) removes any of the given characters from both ends, which is why 'happy.py'.strip('.py') eats into the word itself and returns 'ha'. removeprefix and removesuffix remove an exact substring.

f-string format specs

from datetime import date

name, amount, rate = "Asha", 1234567.891, 0.0725
print(f"{name!r} paid Rs {amount:,.2f}")
print(f"Interest: {rate:.1%}")
print(f"[{name:>8}] [{name:<8}] [{name:^8}]")
print(f"Order #{42:05d}")
print(f"{date(2026, 10, 12):%d-%m-%Y}")
total = 1500
print(f"{total=}")

The part after the colon is a format spec: , for thousands separators, .2f for decimals, % for percentages, alignment with < > ^ and zero padding with 05d.

Building strings efficiently

rows = [("Asha", 500), ("Ravi", 750), ("Meera", 1200)]

# Slow pattern in a long loop: repeated concatenation
out = ""
for n, amt in rows:
    out += f"{n}:{amt};"

# Preferred: build parts, join once
fast = ";".join(f"{n}:{amt}" for n, amt in rows)
print(fast)

join computes the final size once and copies each piece a single time, so it stays linear even for large inputs.

Key points

Common follow-up questions

Interview tips

Concepts covered

Strings, Immutability, Slicing, String Methods, f-strings, Unicode

More Python Interview questions