Python String Methods
Clean text, split and join strings, and format numbers with f-strings.
Why it matters: Prompt cleanup and readable metric logs are string work.
Basics
Useful Methods
Strings are immutable. Every method returns a new string.
Useful methods:
lower(),upper()strip()find(),startswith()split(),join(),replace()
Prefer " ".join(parts) over += in a loop.
Tiny example
Strip, lower, and split a string.
raw = " Hello GenAI "
clean = raw.strip().lower()
print(clean)
print(clean.split())Basics
Format Specifiers
Inside an f-string, text after : is a format spec:
:.2f- two decimals:.1%- percent:,- thousands separator
Common mistake: forgetting to assign the result of a string method.
Tiny example
Format a score and a latency.
score = 0.913
latency = 1280
print(f"{score:.1%}")
print(f"{latency:,} ms")Basics
Multi-line Text
Triple quotes keep newlines and work well for prompts.
Common escapes: \n, \t, \\.
Raw strings (r"...") turn escapes off.
Tiny example
A short prompt with a newline.
prompt = "System: be brief\nUser: what is RAG?"
print(prompt)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: clean a document
Strip, lower, and collapse spaces.
In AI / ML: Pipelines often normalise text before embedding.
example.py
Python
raw = " The QUICK brown Fox "
clean = " ".join(raw.strip().lower().split())
print(clean)AI / ML example 2
AI / ML: format a metric
Make scores easy to read.
In AI / ML: Eval reports print accuracy and latency with format specs.
example.py
Python
acc = 0.913
latency = 128
print(f"acc={acc:.1%} latency={latency}ms")Takeaways
- 1String methods return new strings.
- 2Prefer join() over += in a loop.
- 3f-string specs like :.2f and :.1% make reports readable.