Autocoder

Python String Interview Questions

Last updated 2026-11-19

String questions appear in nearly every Python screening test because they combine language knowledge with simple algorithms. You may be asked about immutability and the cost of concatenation, about formatting and Unicode, and then handed a problem such as reversing words or checking anagrams.

The answers below cover the methods interviewers actually ask about, with the traps that produce wrong output: strip versus replace, split with and without arguments, bytes versus str, and comparing strings in a case-insensitive way.

LevelFresher to 2 years
Focusstr methods, formatting, text algorithms
VersionPython 3.8 and later

Habits that score well

Say that strings are immutable before writing any string-building loop, and reach for join. Name the complexity of your solution, and mention that Python 3 strings are sequences of Unicode code points.

Related practice

Algorithmic string problems are covered in string interview questions. Core language questions are on the Python interview questions page.

Python String Interview Questions: questions with worked answers

  1. 1

    Are Python strings mutable? What does that imply?

    easy

    No. A str cannot be changed in place, so s[0] = 'x' raises TypeError, and methods such as upper() or replace() return new strings. The result is that repeated concatenation in a loop may copy characters repeatedly. CPython sometimes optimises s += x when the string has a single reference, but you should not rely on it. Collect pieces in a list and call ''.join(pieces), which is O(total length).

    python
    s = "hello"
    t = s.upper()
    print(s, t)          # hello HELLO
    s[0] = "j"           # TypeError: 'str' object does not support item assignment
  2. 2

    How do you reverse a string, and check whether it is a palindrome?

    easy

    Use slicing with a negative step: s[::-1], O(n) time and space. A palindrome check compares s with its reverse. For sentences, normalise first by keeping only alphanumeric characters and lowercasing. A two-pointer loop does the check in O(1) extra space.

    python
    def is_pal(s):
        t = [c.lower() for c in s if c.isalnum()]
        return t == t[::-1]
    
    print("abc"[::-1])                              # cba
    print(is_pal("A man, a plan, a canal: Panama")) # True
  3. 3

    What is the difference between split() with and without an argument?

    easy

    Without an argument, split() splits on any run of whitespace and drops empty strings from the ends. With an explicit separator, split(' ') splits at every occurrence, so consecutive separators produce empty strings. maxsplit limits the number of splits. rsplit works from the right and splitlines splits on line boundaries.

    python
    s = "  a  b "
    print(s.split())        # ['a', 'b']
    print(s.split(" "))     # ['', '', 'a', '', 'b', '']
    print("a,b,c".split(",", 1))   # ['a', 'b,c']
  4. 4

    Explain join and why it is faster than concatenation in a loop.

    medium

    sep.join(iterable) calls the method on the separator and requires every item to be a str, otherwise TypeError. It computes the total length once and allocates the result once, so it is linear. Concatenating in a loop can degrade to quadratic time on implementations without the in-place optimisation.

    python
    parts = ["a", "b", "c"]
    print("-".join(parts))            # a-b-c
    print("".join(str(i) for i in range(5)))   # 01234
    print(",".join([1, 2]))           # TypeError
  5. 5

    What are the ways to format strings, and which should you prefer?

    medium

    There are three: old-style percent formatting, str.format with braces, and f-strings from Python 3.6. F-strings are the fastest and most readable, evaluate expressions inline, and support format specs after a colon, such as width, precision and thousands separators. Use str.format or string.Template when the template is stored outside the code. For logging, pass arguments to the logger rather than formatting eagerly.

    python
    name, n = "Asha", 1234.5678
    print(f"{name} owes {n:,.2f}")     # Asha owes 1,234.57
    print(f"{7:03d} {0.256:.1%}")      # 007 25.6%
    print(f"{name!r:>8}")              # 'Asha'  right-aligned in 8
  6. 6

    What is the difference between strip, lstrip, rstrip and replace?

    medium

    strip removes characters from both ends only, never from the middle. Its argument is a set of characters, not a substring, so 'xxabcxx'.strip('x') gives 'abc' and 'abcba'.strip('ab') gives 'c'. replace(old, new) substitutes every occurrence anywhere and accepts a count. To remove a prefix or suffix as a substring use removeprefix and removesuffix, available from Python 3.9.

    python
    print("abcba".strip("ab"))           # c
    print("a b  c".replace(" ", ""))     # abc
    print("test_file.py".removesuffix(".py"))   # test_file
  7. 7

    How do you check whether two strings are anagrams?

    medium

    Two strings are anagrams if they have the same multiset of characters. Sorting both is O(n log n). Counting characters with collections.Counter is O(n) time and O(k) space for k distinct characters. Normalise case and ignore spaces if the problem says so, and compare lengths first as a cheap early exit.

    python
    from collections import Counter
    def anagram(a, b):
        return Counter(a) == Counter(b)
    print(anagram("listen", "silent"))   # True
    print(anagram("aab", "abb"))         # False
  8. 8

    What is the difference between str and bytes, and what are encode and decode?

    medium

    A str is a sequence of Unicode code points. bytes is a sequence of integers 0 to 255. encode turns a str into bytes using a codec, usually UTF-8, and decode does the reverse. The length of the encoded form can differ from the character count because UTF-8 uses one to four bytes per code point. Mixing str and bytes raises TypeError, and decoding with the wrong codec raises UnicodeDecodeError.

    python
    s = "café"
    b = s.encode("utf-8")
    print(len(s), len(b), b)    # 4 5 b'caf\xc3\xa9'
    print(b.decode("utf-8"))    # café
  9. 9

    Predict the output of these string comparisons and identity checks.

    hard

    Strings compare lexicographically by code point, so uppercase letters sort before lowercase and '10' < '9'. The is operator tests identity, and CPython may intern some strings, so two equal literals can be the same object while strings built at runtime usually are not. Always use == for values.

    python
    print("a" < "B", "10" < "9", "abc" < "abd")   # False True True
    a = "hello world"
    b = "hello " + "world"
    c = "".join(["hello", " world"])
    print(a == c, a is c)    # True False
  10. 10

    How do you count the occurrences of a character or substring?

    easy

    s.count(sub) returns the number of non-overlapping occurrences. For overlapping matches, loop with find and a moving start, or use a regular expression with a lookahead. collections.Counter(s) gives frequencies of every character at once.

    python
    print("banana".count("a"))     # 3
    print("aaaa".count("aa"))      # 2  (non-overlapping)
  11. 11

    How would you reverse the words of a sentence, and then each word in place?

    medium

    Split on whitespace, reverse the list, and join: ' '.join(s.split()[::-1]). This also collapses extra spaces. To reverse the characters of each word instead, apply [::-1] to each word. Both are O(n). Interviewers sometimes ask for the O(1)-space version on a character array, which reverses the whole array and then each word.

    python
    s = "the sky  is blue"
    print(" ".join(s.split()[::-1]))              # blue is sky the
    print(" ".join(w[::-1] for w in s.split()))   # eht yks si eulb
  12. 12

    Find the first non-repeating character in a string.

    hard

    Count frequencies in one pass, then scan again in original order to find the first character with count 1. This is O(n) time and O(k) space for k distinct characters. Return -1 or None when there is none. A single pass with an ordered dictionary also works, but two passes are easier to explain.

    python
    from collections import Counter
    def first_unique(s):
        cnt = Counter(s)
        for i, ch in enumerate(s):
            if cnt[ch] == 1:
                return i
        return -1
    print(first_unique("leetcode"))   # 0
    print(first_unique("aabb"))       # -1
  13. 13

    What do isalpha, isdigit, isnumeric and isalnum check, and where do they surprise you?

    medium

    isalpha is True for non-empty strings of letters, isdigit for digit characters, isalnum for letters or digits, and isnumeric also accepts things like fractions and Roman numeral characters. All return False for an empty string. isdigit and isnumeric accept non-ASCII digits, so to validate input as a plain integer, combine with ASCII checks or just try int() and catch ValueError. int() does not accept spaces inside the string but ignores outer whitespace.

    python
    print("".isalpha(), "12".isdigit(), "²".isdigit(), "½".isnumeric())
    # False True True True
    print(int(" 42 "))      # 42
  14. 14

    How do you check whether one string is a rotation of another?

    hard

    If the lengths are equal, s2 is a rotation of s1 exactly when s2 occurs inside s1 + s1. This works because every rotation is a substring of the doubled string. With the built-in in operator it runs in practice in roughly linear time. Always check the lengths first, otherwise 'ab' would match inside 'abab' wrongly.

    python
    def is_rotation(a, b):
        return len(a) == len(b) and b in a + a
    print(is_rotation("waterbottle", "erbottlewat"))   # True
    print(is_rotation("abc", "acb"))                   # False

Frequently asked questions

Why can't I change a character in a Python string?

Strings are immutable. Convert to a list of characters, change the item, then join back, or build a new string with slicing.

What is the difference between find and index?

Both return the first position of a substring. find returns -1 when absent, whereas index raises ValueError.

How do I compare strings ignoring case?

Use a.casefold() == b.casefold(). It handles more Unicode cases than lower(), for example the German sharp s.

How long is a Python string if it contains emoji?

len counts code points, so one emoji is usually 1, though some emoji built from several code points report a larger length.

Related guides

More in Programming Language Interview Questions by Language

See all in this section