Home/Learn/Python A–Z/Strings Deep-Dive — Methods, Formatting & Unicode

Strings Deep-Dive — Methods, Formatting & Unicode

Intermediate
Modern Python

The string methods that solve interview problems — split/join/strip/find/replace, is* checks, format specs — plus the bytes-vs-str boundary every backend engineer must respect.

Overview

String manipulation is the most common category of easy-round interview questions, and Python's method set solves most of them without algorithms: split/join for tokenizing, strip for cleaning, startswith/endswith accepting tuples, count/find/replace for searching. Underneath, str is immutable Unicode; bytes is raw binary — encode() and decode() cross the boundary, and mixing them up is the classic production bug when APIs, files, and networks meet.

The Method Toolbox

These 15 methods solve 80% of string questions. Note split() with no args handles multiple spaces; join is called ON the separator; translate strips characters fastest.

The 80% toolbox
s = "  AiCanCode: Campus to Corporate  "

print(s.strip())                    # trim both ends
print(s.lower().count("c"))         # 4
print(s.replace("Corporate", "Job"))

# split/join — the tokenize/detokenize pair
csv_row = "asha,24,pune"
parts = csv_row.split(",")          # ['asha', '24', 'pune']
print("|".join(parts))              # asha|24|pune
words = "to  be   or  not".split() # no arg: any whitespace runs
print(words)                        # ['to','be','or','not']

# Prefix/suffix — tuples allowed!
f = "report.xlsx"
print(f.endswith((".xls", ".xlsx")))   # True
print(f.removesuffix(".xlsx"))         # report (3.9+)

# Char-class checks
print("2026".isdigit(), "abc".isalpha(), "a1".isalnum())

# Case-insensitive compare — use casefold, not lower
print("STRASSE".casefold() == "strasse".casefold())

# Palindrome check, the pythonic way
t = "Malayalam".lower()
print(t == t[::-1])                 # True

str vs bytes — the Encoding Boundary

str = Unicode text (what you manipulate); bytes = raw binary (what networks/files/APIs move). encode() to send, decode() to read. UTF-8 everywhere unless told otherwise.

encode/decode — text vs binary, never mix
text = "नमस्ते Python"          # str — Unicode, len counts CHARACTERS
print(len(text))                    # 13

data = text.encode("utf-8")        # bytes — len counts BYTES
print(len(data))                    # 25 — Devanagari chars take 3 bytes
print(type(data))                   # <class 'bytes'>

back = data.decode("utf-8")        # bytes -> str
print(back == text)                 # True

# The classic bug:
# "abc" + b"def"          -> TypeError: can't concat str to bytes
# open a file wrongly and .read() returns bytes when you expected str

# ord/chr — code points (shows up in cipher problems)
print(ord("A"), chr(66))            # 65 B
shifted = "".join(chr((ord(c) - 97 + 3) % 26 + 97) for c in "attack")
print(shifted)                       # dwwdfn — Caesar +3

Key Points to Remember

  • 1split() no-arg splits on whitespace runs; sep.join(list) — separator is the caller
  • 2startswith/endswith accept tuples; removeprefix/removesuffix since 3.9
  • 3str is Unicode text; bytes is binary — encode()/decode() with explicit utf-8
  • 4s == s[::-1] for palindromes; casefold() for caseless comparison

Interview Questions

Sign in to ask Aria
1

Reverse words in a sentence in one line — and explain the split/join pair.

EasyAccenture
2

What is the difference between str and bytes? What does encode() return?

MediumPhonePe
3

Why can len(text) and len(text.encode()) differ?

MediumOracle

Ask Aria about Strings Deep-Dive — Methods, Formatting & Unicode

Your personal AI tutor — ask anything about this concept

Revision Status

Personal Notes

Sign in to save personal notes for this topic.

Discussion

Sign in to join the discussion.

Loading discussion…