Skip to the solution
EasyDSA13 min read

What are common useful string methods?

1.1k views

The problem

Question presented to candidate: "You get messy text from a CSV export or a user form. Which string methods do you reach for to clean it, split it, search it and put it back together, and what are the traps in them?"

What a strong answer should cover:

  • Strings are immutable: every method returns a new string, so you must use the return value (s.strip() alone does nothing to s).
  • The cleaning and splitting core: strip/lstrip/rstrip, split (with and without an argument, maxsplit), rsplit, partition, splitlines, and sep.join(iterable) as the inverse of split.
  • Searching and testing: in, find (returns -1) versus index (raises ValueError), count, startswith/endswith with a tuple, and the isdecimal/isdigit/isnumeric differences.
  • The strip(chars) trap β€” the argument is a set of characters β€” and removeprefix/removesuffix (Python 3.9, PEP 616) as the fix.
  • Case handling: lower versus casefold for caseless comparison; title() surprises; padding with zfill, center, ljust, rjust; translate for many single-character replacements.
  • Building strings with "".join(parts) rather than += in a loop, and why (CPython has an in-place shortcut, but it is not guaranteed).

Code / implementation expected: Optional β€” a short cleaning snippet (strip, split, join) is enough; bonus for showing the rstrip(".txt") trap.

  • string-methods

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

13 min read Β· 12 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

PythonCleaning, splitting and joining (plus the strip trap)
PythonSearching, digit tests, casefold, padding and translate

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 1 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextEasy

What is the difference between '==' and 'is'?

Continue