Strings
Work with text — joining, slicing, and handy methods.
What you will learn
- Join and format strings
- Use f-strings
- Use string methods
f-strings: the easy way to build text
A string is just text. Often you want to mix variables into a sentence. The cleanest way is an f-string: put an f right before the opening quote and drop variable names inside { } — Python swaps in their values for you.
name = "Asha"
score = 95
print(f"{name} scored {score}%")The f tells Python “this string has slots to fill.” When it runs, {name} is replaced by the value of name (Asha) and {score} by 95. The % is plain text and stays as-is, so you get one tidy sentence — no clumsy + joining or commas needed.
Note: Output: Asha scored 95%
Useful string methods
Strings come with built-in methods — little tools you call with a dot after the text to clean or transform it. Here are four you will use constantly:
text = " CodingClave "
print(text.strip()) # remove spaces -> "CodingClave"
print(text.upper()) # " CODINGCLAVE "
print("a,b,c".split(",")) # ['a', 'b', 'c']
print(len("hello")) # 5Going line by line: .strip() removes the extra spaces from the start and end, leaving CodingClave. .upper() turns every letter to capitals (the spaces stay, since we used the original text). .split(",") chops a string wherever it finds a comma and gives back a list of the pieces, ['a', 'b', 'c']. Finally len("hello") is not a method but a function that counts the characters — hello has 5.
Note: Output: CodingClave CODINGCLAVE ['a', 'b', 'c'] 5
Q. How do you put a variable inside a string the modern way?
✍️ Practice
- Use an f-string to greet someone by name and age.
- Clean a messy string with
strip()andupper().
🏠 Homework
- Take a full name and print the initials using split().