Strings and text
Text is the raw material of NLP and GenAI. Learn quotes, f-strings, slicing, and the methods you will use on prompts and documents.
Why this matters in AI / ML / GenAI
Prompts, system messages, retrieved chunks, JSON payloads, and log lines are all strings. Token counts correlate with length. Cleaning whitespace and building prompts with f-strings is daily work for GenAI engineers.
Creating and combining strings
Use single or double quotes. For multi-line text (prompts, docs) use triple quotes """...""".
Concatenate with +, or better, f-strings: f"Model {name} scored {score:.2f}". F-strings keep prompts readable.
len(s) is the number of characters, not tokens. Character length is still a useful proxy when you do not have a tokenizer loaded.
Strings are immutable. s.upper() returns a new string; s does not change unless you assign the result back.
Slicing, splitting, and stripping
Indexing: s[0] is the first character. s[-1] is the last. Slices: s[0:50] is the first 50 characters (end index is exclusive).
split() breaks on whitespace by default — useful for a crude word count. strip() removes leading/trailing whitespace, which you should do on every user prompt before sending it to a model.
in checks substring membership: "error" in message.lower().
Escape sequences: \n is a newline. In prompts, extra blank lines change model behaviour more than people expect — keep prompt templates tidy.
Copy-paste examples
Copy into your own editor, or load one into the compiler below and press Run.
F-string prompt template
This is the pattern behind most LLM wrappers before you add a library.
user_question = "What is MLOps?"
context = "MLOps is how teams deploy and monitor ML models."
prompt = f"""You are a precise assistant.
Use only the context.
Context:
{context}
Question: {user_question}
Answer:"""
print(prompt)
print("---")
print("characters:", len(prompt))Clean user text before it hits a model
strip, lower, and a length guard prevent empty or huge prompts.
raw = " What is RAG? \n"
clean = raw.strip()
print(repr(raw))
print(repr(clean))
print("empty?", clean == "")
print("too long?", len(clean) > 4000)
print("words (rough):", len(clean.split()))Slice a long document into a preview
End index is exclusive. Add an ellipsis when truncated.
doc = "Retrieval-Augmented Generation grounds an LLM in your own documents."
preview = doc[:40]
print(preview + ("..." if len(doc) > 40 else ""))
print("starts with Retrieval?", doc.startswith("Retrieval"))
print("mentions LLM?", "LLM" in doc)Build a system + user prompt
Try it — in-browser Python
Edit the context and question, then print character counts for each part.
Output
Python runs in your browser. First run downloads the runtime.
Press Run (or Ctrl+Enter) to execute.
CPython in WebAssembly. Stdlib works. NumPy and pandas load on demand. No input(), no GPU, no network installs.
Takeaways
- f-strings are the clean way to build prompts and log lines.
- strip() user text; len() is characters, not tokens.
- Strings never change in place — methods return new strings.