# Strings & String Methods

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

Canonical: https://www.internhack.in/learn/interview/python-interview/python-strings
Last updated: 2026-11-28

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.

- `s[0]`, `s[-1]`: first and last character
- `s[:3]`, `s[3:]`: prefix and the rest
- `s[::-1]`: reversed string (a common palindrome check)
- `s[::2]`: every second character

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

### Methods you will actually use

| Task | Method |
| --- | --- |
| Clean input | `strip()`, `lstrip()`, `rstrip()` |
| Change case | `lower()`, `upper()`, `title()`, `casefold()` for case-insensitive compare |
| Split and join | `split()`, `split(",")`, `rsplit(maxsplit=1)`, `"-".join(items)` |
| Search | `in`, `find()` (returns -1), `index()` (raises), `count()`, `startswith()`, `endswith()` |
| Replace | `replace(old, new, count)` |
| Prefix/suffix | `removeprefix()`, `removesuffix()` (Python 3.9+) |
| Validate | `isdigit()`, `isalpha()`, `isalnum()`, `isspace()` |
| Pad | `zfill()`, `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

- str is an immutable sequence of Unicode code points; methods return new strings
- Use ''.join(parts) instead of += in loops
- strip(chars) removes a set of characters; removeprefix/removesuffix remove exact text
- f-strings support format specs (:.2f, :,, :>8, :%) and {var=} for debugging
- Python 3.12 relaxed f-string quoting; 3.14 added t-strings (PEP 750)

## Common follow-up questions

- Why are strings immutable in Python, and what are the benefits?
- What is the difference between find() and index()?
- How would you check if two strings are anagrams in O(n)?
- What is the difference between str and bytes, and when do you encode?
- What problem do t-strings solve that f-strings do not?

## Interview tips

- Mention immutability first, then the join-vs-concatenation performance point
- The strip vs removeprefix gotcha is a quick way to show real-world experience
- For coding rounds, state the complexity of your string solution out loud

## Concepts covered

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

Previous: [Variables & Data Types](https://www.internhack.in/learn/interview/python-interview/python-variables-types) · Next: [Lists, Tuples & Sets](https://www.internhack.in/learn/interview/python-interview/python-lists-tuples-sets) · [All of Python Interview](https://www.internhack.in/learn/interview/python-interview)

## More Python Interview questions

- [Dictionaries & Operations](https://www.internhack.in/learn/interview/python-interview/python-dictionaries)
- [Control Flow & Loops](https://www.internhack.in/learn/interview/python-interview/python-control-flow)
- [Functions & Arguments](https://www.internhack.in/learn/interview/python-interview/python-functions)
- [\*args & kwargs](https://www.internhack.in/learn/interview/python-interview/python-args-kwargs)
- [List Comprehensions](https://www.internhack.in/learn/interview/python-interview/python-list-comprehensions)
- [Lambda, Map, Filter, Reduce](https://www.internhack.in/learn/interview/python-interview/python-lambda-map-filter)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [Python Interview](https://www.internhack.in/learn/interview/python-interview)
