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.
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
- The first character of a string has index 0, and negative indices count from the right.
- A slice s[a:b] includes the start and leaves out the end.
- Strings are immutable, so methods like strip() and lower() return a new string.
- split() returns a list of words, and join() glues a list of strings together.
- An f-string is a string literal prefixed with f. It can hold expressions in curly braces, evaluated at run time.
- After the colon in a replacement field comes a format spec. In the example, :.2f printed 0.91234 as 0.91.
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
elThe 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_interestedupper() returns a new string. The original s is unchanged.
3. What does this print?
print(f"{3.14159:.2f}")Show the answer
3.14The 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).
Strings can be indexed (subscripted), with the first character having index 0.
docs.python.org/3.12/tutorial/introduction.html — Strings can be indexed from 0, and negative indices count from the right.Indices may also be negative numbers, to start counting from the right:
docs.python.org/3.12/tutorial/introduction.html — Negative string indices count from the right.Note how the start is always included, and the end always excluded.
docs.python.org/3.12/tutorial/introduction.html — A slice includes its start and excludes its end.Python strings cannot be changed - they are immutable .
docs.python.org/3.12/tutorial/introduction.html — Strings are immutable.Therefore, assigning to an indexed position in the string results in an error:
docs.python.org/3.12/tutorial/introduction.html — Assigning to a string position gives an error.Return a copy of the string with the leading and trailing characters removed.
docs.python.org/3.12/library/stdtypes.html — strip() returns a copy with edge characters removed.Return a list of the words in the string, using sep as the delimiter string.
docs.python.org/3.12/library/stdtypes.html — split() returns a list of words.Return a string which is the concatenation of the strings in iterable .
docs.python.org/3.12/library/stdtypes.html — join() concatenates the strings of an iterable.Return a copy of the string with all the cased characters [ 4 ] converted to lowercase.
docs.python.org/3.12/library/stdtypes.html — lower() returns a lowercase copy.A formatted string literal or f-string is a string literal that is prefixed with 'f' or 'F' . These strings may contain replacement fields, which are expressions delimited by curly braces {} . While other string literals always have a constant value, formatted strings are really expressions evaluated at run time.
docs.python.org/3.12/reference/lexical_analysis.html — f-strings are prefixed with f and contain replacement fields evaluated at run time.and a format_spec , which is preceded by a colon ':' .
docs.python.org/3.12/library/string.html — A format_spec follows a colon.