Strings, slices and f-strings
A string is a sequence of characters, and each character has a position called an index. Python counts from 0, not 1.
word = "python"
# 012345
word[0] # 'p'
word[5] # 'n'
word[-1] # 'n' negative indexes count from the end
len(word) gives the length, 6. Asking for word[6] is an IndexError: the last index is always len - 1.
A slice grabs a chunk: word[start:stop]. It includes start but stops before stop. So word[0:2] is "py". Leave a side empty to mean "from the beginning" or "to the end": word[2:] is "thon", word[:-1] is "pytho".
Strings come with methods, functions you call with a dot:
s.upper()ands.lower()change case.s.strip()removes spaces from both ends.s.replace("a", "b")swaps text.s.count("o")counts how many times something appears.
Here is the catch: strings are immutable. Methods never change the original; they give you back a new string. name.upper() on its own line does nothing useful. You need name = name.upper() to keep the result.
To build text from variables, use an f-string: put f before the quote and drop variables into { }.
age = 15
print(f"I am {age} and next year I'll be {age + 1}")
You can put any expression inside the braces, and {price:.2f} shows a number with exactly 2 decimal places. Way nicer than gluing strings with +, which also refuses to mix strings and numbers.
Try it yourself
Edit it. Break it. Run it again.word = "python"
print(word[0], word[-1]) # first and last letters
print(word[0:2], word[2:]) # slices
print(len(word))
shout = word.upper() # word itself is unchanged
print(word, shout)
name = " Sam "
print("[" + name.strip() + "]")
price = 4.5
print(f"{word} costs {price:.2f} and has {len(word)} letters")
Your turn
Type it yourself. That is the whole trick.1Initials
Using indexing on first and last, print the initials of the name, with a dot after each, so the output is exactly A.L. Use an f-string.
first = "Ada"
last = "Lovelace"
print(f"{first}.{last}.")
2Tidy username
raw is a messy username. Strip the spaces off both ends and make it lowercase, then print it, so the output is exactly gamer_kid. Remember that string methods return a new string.
raw = " GaMeR_KiD " raw.strip() print(raw)