Beginner·20 min·0/47 done

Python Strings

Create strings, use f-strings, slice text, and clean whitespace.

Why it matters: Prompts, chunks, and log lines are all strings.

Basics

Creating Strings

Use single or double quotes. Use triple quotes for multi-line text.

Prefer f-strings: f"Model {name}"

len(s) counts characters.

Strings are immutable. s.upper() returns a new string. Common mistake: expecting s.upper() to change s in place.

Tiny example

Make a string and print its length.

name = "RAG"
print(name)
print(len(name))

Basics

Slicing and Cleaning

s[0] is the first character. s[-1] is the last.

s[0:5] is the first 5 characters (end index not included).

strip() removes leading and trailing spaces. split() breaks text into a list of words. Common mistake: sending padded text to a model without stripping.

Tiny example

Strip spaces, then take a slice.

text = "  Hello GenAI  "
clean = text.strip()
print(clean)
print(clean[:5])

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: f-string prompt

Put variables into a prompt with curly braces.

In AI / ML: Chat apps build prompts from system text and user questions.

example.py

Python

question = "What is MLOps?"
context = "MLOps deploys and monitors models."
prompt = f"Context: {context}\nQ: {question}"
print(prompt)

AI / ML example 2

AI / ML: clean user text

strip() removes extra spaces before a model call.

In AI / ML: Before RAG or chat, engineers strip and reject empty prompts.

example.py

Python

raw = "   What is RAG?   "
clean = raw.strip()
print(clean)
print(clean == "")

Takeaways

  • 1f-strings are the clean way to build text.
  • 2strip() cleans spaces. len() counts characters.
  • 3String methods return new strings.
Certificate