Python for AIPython 3.10+ · Pydantic 2.12
0%
1
Curious builder0 XP earned · 300 to level 2
0 daysFinish a lesson to begin
Badge collection0 of 6 unlocked
33 small wins to finish your pathNext lesson

Strings: working with text

Almost everything sent to or from a model is text. Python calls a piece of text a string, and gives every string a set of tools for cleaning and changing it.

Example
ticket = "  My parcel has NOT arrived  "
print(len(ticket))

clean = ticket.strip()
print(clean)
print(len(clean))

len counts characters, spaces included. strip removes the spaces at both ends, which is why the length drops.

ticket.strip() is a method: an action that belongs to a value, called with a dot. It gives back a new string. The original ticket still has its spaces.

Example
print(clean.lower())
print(clean.upper())
print("arrived" in clean.lower())
print("refund" in clean.lower())

in asks whether one piece of text appears inside another, and answers True or False. Lowering the ticket first means NOT, Not and not all match.

f-strings: putting values into text

Example
customer = "Ben"
ticket_id = 2
print(f"Hello {customer}, we are looking at ticket {ticket_id}.")

An f before the opening quote makes an f-string. Each {name} inside is replaced by that variable's value, even when the value is a number.

Building a prompt

A prompt is the text you send to a model. Most prompts are a fixed instruction with some data put into it, which is exactly what an f-string does.

Example
ticket = "My parcel has not arrived"
prompt = f"Sort this ticket into billing, shipping or other.\nTicket: {ticket}"
print(prompt)

\n inside a string means a new line. It is two characters in the code and one line break in the output.

Try it yourself
  • Use clean.replace("parcel", "order") and print the result.
  • Put {customer} into the prompt as well.
  • Remove the f from the f-string and see what prints instead.

Slow is fine. Stopping is the only problem.