Skip to content

4. Strings

Beginner · 8 min read

Prompts, documents, model replies — GenAI work is mostly text, so strings are worth mastering.

4.1 f-strings (formatting)

name, score = "RAG", 0.8734

print(f"{name} score: {score}")        # → RAG score: 0.8734
print(f"{score:.2f}")                  # → 0.87     2 decimal places
print(f"{score:.0%}")                  # → 87%      as a percentage
print(f"{1234567:,}")                  # → 1,234,567  thousands separator
print(f"{name=}")                      # → name='RAG'  handy for debugging

4.2 Indexing and slicing

text = "retrieval"

print(text[0])        # → r      first character (indexes start at 0)
print(text[-1])       # → l      last character
print(text[0:3])      # → ret    start included, end excluded
print(text[3:])       # → rieval    from index 3 to the end
print(text[::-1])     # → laveirter  reversed

Strings are immutable — methods return a new string instead of changing the original.

4.3 Common methods

raw = "  Hello, GenAI World!  "

print(raw.strip())                 # → Hello, GenAI World!   remove surrounding spaces
print(raw.lower().strip())         # → hello, genai world!
print(raw.strip().replace("World", "Learners"))   # → Hello, GenAI Learners!
print("genai" in raw.lower())      # → True
print(raw.strip().startswith("Hello"))            # → True
print("report.pdf".endswith(".pdf"))              # → True
print("RAG".center(9, "-"))        # → ---RAG---

4.4 Split and join

sentence = "chunk the text into words"

words = sentence.split()           # split on whitespace → list of words
print(words)                       # → ['chunk', 'the', 'text', 'into', 'words']
print(len(words))                  # → 5

csv_line = "name,email,score"
print(csv_line.split(","))         # → ['name', 'email', 'score']

print(" ".join(words[:2]))         # → chunk the      join a list back into one string
print("\n".join(["a", "b"]).count("\n"))   # → 1      "\n" is a newline

4.5 Multi-line prompts

context = "Refunds are allowed within 30 days."
question = "Can I return after 3 weeks?"

# Triple-quoted f-string: keeps line breaks, fills in variables.
prompt = f"""Answer only from the context.

Context: {context}
Question: {question}"""

print(prompt.splitlines()[0])      # → Answer only from the context.

Why it matters for GenAI

Prompt templates are f-strings; cleaning scraped text is strip(), replace() and split(); and chunking documents starts with text.split().

Practice

  • Given " RAG,Agents ,LLMOps ", produce the list ['rag', 'agents', 'llmops'].
Answer
raw = "  RAG,Agents ,LLMOps  "
print([t.strip().lower() for t in raw.split(",")])   # → ['rag', 'agents', 'llmops']