String methods reference
String methods for cleaning, searching, splitting, and formatting.
Why it matters: Prompts, logs, and scraped text are strings. Cleanup and f-strings are daily GenAI work.
Basics
Clean and case
Strings are immutable. Methods return a new string. Forgetting to assign is a common bug.
Useful: strip, lower, upper, casefold, removeprefix, removesuffix.
Note: strip("abc") removes those characters from the ends, not the substring "abc".
Tiny example
Strip and lower messy text.
text = " Hello GenAI "
clean = text.strip().lower()
print(repr(clean))Basics
Search and test
in, find (-1 if missing), index (raises), startswith, endswith, count, replace.
Predicates: isdigit, isalpha, isalnum, isspace.
"3.14".isdigit() is False. Prefer try: float(s) for numeric checks.
Tiny example
startswith and find on a log line.
line = "ERROR: timeout after 30s"
print(line.startswith("ERROR"))
print(line.find("timeout"))Basics
Split, join, format
split() on whitespace drops empties. split(",") keeps empties. partition(sep) returns three parts - good for key=value.
Prefer "".join(parts) over += in a loop.
f-strings: {x:.2f}, {n:,}, {ratio:.1%}, {name:>10}.
Tiny example
Split tokens and join them back.
parts = "rag,agents,eval".split(",")
print(parts)
print(" | ".join(parts))
print(f"score={0.913:.2f}")Then AI / ML
AI / ML examples
Same idea, used in real AI work. Press Try in lab to run it.
AI / ML example
AI / ML: parse key=value settings
partition is clean for key=value chunks.
In AI / ML: Serving logs and prompt flags are often parsed this way.
example.py
Python
line = "model=gpt-4.1-mini,temp=0.2,stream=true"
settings = {}
for chunk in line.split(","):
key, sep, value = chunk.partition("=")
if sep:
settings[key] = value
print(settings)AI / ML example 2
AI / ML: format eval scores
f-string specs for reports and logs.
In AI / ML: Accuracy, cost, and latency usually print with fixed decimals.
example.py
Python
score = 0.9137
tokens = 1234567
name = "mini"
print(f"{name} acc={score:.1%} tokens={tokens:,}")
print(f"{score=}")Takeaways
- 1Strings are immutable - assign method results.
- 2Use join to build strings; partition for key=value.
- 3f-string specs cover most formatting needs.