hayaliv

hayaliv / Hi! Python / Level 0

Strings and f-strings

Strings are text you can index, slice, clean with methods, and fill in with f-strings.

Hi! Python · Level 0: Python core · Checked against the Python 3.12 documentation · Updated 2026-10-17

Think of it like this

A string is like a row of beads on a necklace. Each bead has a position, and you can read any bead or a stretch of beads without breaking the necklace.

Where the analogy stops being true. You can restring a real necklace, but a Python string cannot be changed after it is made.

What to know

Example

reply = "  Sure, Let's meet Tuesday!  "
clean = reply.strip()
print(clean)
print(clean.lower())
print(clean[0], clean[-1], clean[:4])
words = clean.lower().split()
print(words)
print("-".join(words))
score = 0.91234
print(f"label=meeting_request score={score:.2f}")
print(reply == clean)

It prints:

Sure, Let's meet Tuesday!
sure, let's meet tuesday!
S ! Sure
['sure,', "let's", 'meet', 'tuesday!']
sure,-let's-meet-tuesday!
label=meeting_request score=0.91
False

Predict, then check

1. What does this print?

print("Hello"[1:3])
Show the answer
el

The slice starts at index 1 and stops before index 3, so it holds the characters at positions 1 and 2.

2. What does this print?

s = "not_interested"
print(s.upper())
print(s)
Show the answer
NOT_INTERESTED
not_interested

upper() returns a new string. The original s is unchanged.

3. What does this print?

print(f"{3.14159:.2f}")
Show the answer
3.14

The format spec .2f shows the number with two digits after the decimal point.

Try it

Write clean_reply(text) that removes spaces and newlines from both ends of text and makes it lowercase.

def clean_reply(text):
    return text
Show a solution
def clean_reply(text):
    return text.strip().lower()

Common mistake

Assigning to a position in a string, such as word[0] = 'J', raises an error because strings cannot be changed.

In a small-language-model project

In a fine-tuning project you usually clean and lowercase reply text before counting words or building prompts, and f-strings are a handy way to build a prompt from a template.

Sources

Each quote below appears word for word on the cited page of the official Python documentation (version 3.12).

Step through this lesson in the Hi! Python desktop

← Values, variables and typesLists, tuples, dicts and sets →