0Pricing
DSA Interview Prep · Lesson

Python String API for Interviews

Work through split, join, replace, find, ord/chr, and string formatting patterns that appear in interview problems involving parsing and transformation.

Strings Are Immutable in Python

Python strings are immutable — you cannot change a character in place. Every string operation that appears to modify a string actually creates a new one. This means s[0] = 'X' raises a TypeError. When you need in-place manipulation, convert to a list of characters first, do your work, then ''.join(chars) to reconstruct. This is the standard interview pattern for string mutation problems.

s = 'hello'
# s[0] = 'H'  # TypeError!

# In-place mutation pattern:
chars = list(s)
chars[0] = 'H'
result = ''.join(chars)
print(result)  # 'Hello'

# Reversing a string
print(s[::-1])           # 'olleh'
print(''.join(reversed(s)))  # 'olleh'

split() and join(): Parsing and Building

s.split(sep) splits a string on a delimiter and returns a list of substrings. sep=None (default) splits on any whitespace and discards empty strings — ideal for parsing space-separated input. 'sep'.join(iterable) concatenates strings with a separator between them. The idiom ' '.join(words) is the efficient way to build a space-separated string from a list — never use + in a loop.

# split
sentence = '  hello   world  '
words = sentence.split()    # ['hello', 'world']
print(words)

csv = 'a,b,c,d'
parts = csv.split(',')      # ['a', 'b', 'c', 'd']
print(parts)

# join
print(' '.join(words))      # 'hello world'
print(','.join(['x','y','z']))  # 'x,y,z'

# Reverse words in a sentence
print(' '.join(sentence.split()[::-1]))  # 'world hello'

All lessons in this course

  1. Python String API for Interviews
  2. Sliding Window for Substrings
  3. Anagrams and Character Frequency Maps
  4. String Encoding, Reversal, and Palindromes
← Back to DSA Interview Prep