Python Basics

Working with Strings

Working With Strings

Text is the main currency of agent work. Prompts are strings, model responses are strings, documents are strings, logs are strings. You will spend more time on text than on numbers.

Making a string

a = "double quotes"
b = 'single quotes'

There is no difference. Pick one and be consistent; most Python code uses double quotes.

Use the other kind when your text contains a quote:

message = "it's fine"
quoted = 'she said "no"'

Multi-line strings

Three quotes let text run over several lines. This is how prompts are written.

system_prompt = """You are an incident triage assistant.

Classify each incident as P1, P2 or P3.
Answer with the severity only."""

print(system_prompt)

Everything between the triple quotes is kept exactly, including the line breaks and the indentation. Be careful with that last part — if you indent a triple-quoted string inside a function, the spaces become part of the text.

f-strings

The way to put values into text.

name = "Priya"
count = 3

print(f"{name} has {count} open tickets")

The f before the quote is what makes the braces work. Forget it and the braces print literally.

You can put any expression inside:

print(f"{name.upper()} — {count * 2} after doubling")
print(f"Cost: {0.4567:.2f}")
print(f"{count:>5}")
  • :.2f — two decimal places
  • :>5 — right-align in five characters

An f-string can be triple-quoted too, which is how most prompts get built:

prompt = f"""You are helping {name}.

Their question is: {question}
Answer in two sentences."""

The methods worth memorising

role = "  Senior Data Architect  "

print(role.strip())
print(role.strip().lower())
print(role.strip().upper())
print(role.strip().title())
print(role.strip().split(" "))
print(role.strip().replace("Senior", "Lead"))
print(len(role.strip()))
MethodDoes
.strip()remove whitespace from both ends
.lower(), .upper()change case
.title()Capitalise Each Word
.split(sep)cut into a list
.join(items)glue a list back together
.replace(a, b)swap text
.startswith(), .endswith()check the ends
.find(x)position, or -1
len(s)length, as a function not a method

Note that len is a function — len(role), not role.len(). That catches Java and C# people every time.

Strings cannot be changed

name = "priya"
name.upper()
print(name)

This prints priya, unchanged. .upper() does not modify the string; it returns a new one. You have to keep it:

name = name.upper()

Every string method works this way. Forgetting it is one of the most common early bugs, and it fails silently — no error, just nothing happening.

Chaining

Because each method returns a new string, you can line them up.

raw = "  RAJESH kumar ,  "
clean = raw.strip().strip(",").strip().title()
print(clean)
Rajesh Kumar

Four methods, one line, and a data-quality problem that people usually fix by hand is gone. This pattern is worth having at your fingertips — messy names, codes and labels turn up in every enterprise extract.

split and join

These two are a pair and they do most of the text work in practice.

line = "P1,network,unassigned"
parts = line.split(",")
print(parts)

back = " | ".join(parts)
print(back)
['P1', 'network', 'unassigned']
P1 | network | unassigned

.split() with no argument splits on any whitespace and ignores repeats, which is usually what you want for prose:

words = "the  server   is down".split()
print(len(words))

Note the direction of .join() — it is called on the separator, not the list. ", ".join(items). This reads backwards at first and is worth saying out loud once.

Searching inside

line = "ERROR code=503 upstream timeout"

print("ERROR" in line)
print(line.startswith("ERROR"))
print(line.find("code="))

in is the one you will use most. It is readable and it is what you want in a log filter:

for line in lines:
    if "ERROR" in line:
        print(line)

Case matters. "error" in line is False here. Lower both sides when you do not care:

if "error" in line.lower():
    ...

Slicing

Take part of a string by position.

text = "Python is a lot of fun"

print(text[0])
print(text[:6])
print(text[7:])
print(text[-3:])
P
Python
is a lot of fun
fun
  • counting starts at 0
  • text[:6] means from the start up to, but not including, position 6
  • negative numbers count from the end

Slicing is used constantly for truncating text to fit a context window:

snippet = document[:2000]

Escapes and raw strings

print("first\nsecond")
print("a\tb")
print("she said \"no\"")
  • \n — new line
  • \t — tab
  • \" — a literal quote
  • \\ — a literal backslash

Windows paths are the usual problem. Put an r in front to switch escapes off:

path = r"C:\Users\Sridhar\data"

Without the r, \U and \d are read as escape sequences and you get an error or the wrong text.

Counting text for a model

Models bill in tokens, not characters, but characters are a usable estimate while you are learning.

print(len(document))
print(len(document) // 4)

Roughly four characters per token in English. Good enough to know whether you are near a limit; use the provider's tokeniser when it matters.

Coming from Java or C#

TaskJava / C#Python
Lengths.length(), s.Lengthlen(s)
CasetoUpperCase(), ToUpper().upper()
Containscontains(), Contains()"x" in s
Splitsplit().split()
JoinString.join(sep, list)sep.join(list)
FormatString.format, $"{x}"f"{x}"
Substringsubstring(0, 6)s[:6]
Trimtrim(), Trim().strip()
Immutable?yesyes

Two things to unlearn: len is a function rather than a method, and join is called on the separator rather than on the collection. C#'s $"{x}" maps almost exactly onto the f-string, so that part will feel familiar.

Common mistakes

  • Forgetting the f on an f-string.
  • Calling a method and discarding the resultname.upper() on its own does nothing.
  • s.len() instead of len(s).
  • list.join(sep) instead of sep.join(list).
  • Case-sensitive comparisons you meant to be case-insensitive.
  • Windows paths without r, giving a unicode escape error.

Practise this

  • Clean a messy name — extra spaces, wrong case, a trailing comma — in one chained line.
  • Split a comma-separated line into parts, then join it back with a different separator.
  • Build a prompt with a triple-quoted f-string containing two variables.
  • Truncate a long piece of text to 200 characters and add an ellipsis if it was cut.

Try It Yourself

Copy this into a new Colab notebook and run it. Nothing to install.

example.py
1# Building AI prompts with f-strings
2user_name = "Alice"
3task = "summarize this article"
4context = "You are a helpful AI assistant"
5
6# Simple f-string
7prompt = f"{context}. The user {user_name} wants you to {task}."
8print(prompt)
9
10# Multi-line prompt template
11system_prompt = f"""
12You are an AI assistant.
13User: {user_name}
14Task: {task}
15
16Guidelines:
17- Be concise
18- Be accurate
19- Be helpful
20"""
21print(system_prompt)
22
23# String methods for cleaning input
24user_input = " SUMMARIZE THIS "
25clean_input = user_input.strip().lower()
26print(f"Cleaned: '{clean_input}'")
27
28# Checking response patterns
29response = "I'll help you summarize that article."
30if response.startswith("I'll help"):
31 print("Assistant acknowledged the task!")