Strings and text processing

You have variables and f-strings down. Now let us learn the string methods that show up in every AI pipeline: len() for checking prompt lengths, join() for combining chunks, and replace() for template substitution.

len() is a built-in function that counts items. For strings, it counts characters. For lists, it counts elements. You will use it constantly to check prompt lengths and count messages.

variables_and_types.py
python
# len() counts items in any collection
menu_item = "Mushroom Burger with Truffle Aioli"
print(f"Characters: {len(menu_item)}")  # 34

# Works on any collection
models = ["gpt-4o", "gemini-2.0-flash", "claude-sonnet"]
print(f"Models available: {len(models)}")  # 3

len() works on strings, lists, dicts, and any collection, and you will use it constantly to check prompt lengths before sending to an LLM.

Two more string methods you will use all the time: join() to combine a list of strings into one, and replace() for simple text substitution. Both are essential for building prompts dynamically.

variables_and_types.py
python
# .join() combines a list into one string
chunks = ["You are a helpful assistant.", "Be concise.", "Use tools."]
system_prompt = "\n".join(chunks)
print(system_prompt)

# .replace() does template substitution
template = "Hello, {name}! Welcome to {course}."
filled = template.replace("{name}", "Param").replace("{course}", "Python for GenAI")
print(filled)

join() combines a list into one string with a separator, perfect for building prompts from chunks. replace() does simple text substitution in templates.

Quiz: Quiz

Loading practice…

Fill in the blanks: Complete the F-string

Loading practice…

Ordering exercise: String processing pipeline

Loading practice…

Validation checklist: Variables and types checklist

Loading practice…