Quest 1 β’ Lesson 7
π€ String Methods & Formatting
Strings are one of the most common data types. Python provides many builtβin methods to manipulate and format strings. This lesson covers the most useful ones.
"Strings are immutable β methods return new strings without modifying the original."
π οΈ Common String Methods
.upper() β uppercase.lower() β lowercase.strip() β remove whitespace from ends.replace(old, new) β replace substring.split(sep) β split into list.join(list) β join list into string.find(sub) β find index of substring.count(sub) β count occurrences.startswith(sub) β check prefix.endswith(sub) β check suffix
string_methods.py
text = " Hello World! "
print(text.upper()) # " HELLO WORLD! "
print(text.lower()) # " hello world! "
print(text.strip()) # "Hello World!"
print(text.replace("World", "Python")) # " Hello Python! "
print(text.split()) # ['Hello', 'World!']
print(",".join(["a","b","c"])) # "a,b,c"
print(text.find("World")) # 7
print(text.count("l")) # 3
print(text.startswith(" He")) # True
print(text.upper()) # " HELLO WORLD! "
print(text.lower()) # " hello world! "
print(text.strip()) # "Hello World!"
print(text.replace("World", "Python")) # " Hello Python! "
print(text.split()) # ['Hello', 'World!']
print(",".join(["a","b","c"])) # "a,b,c"
print(text.find("World")) # 7
print(text.count("l")) # 3
print(text.startswith(" He")) # True
fstring.py
name = "Alice"
age = 30
print(f"My name is {name} and I'm {age} years old.")
# Output: My name is Alice and I'm 30 years old.
age = 30
print(f"My name is {name} and I'm {age} years old.")
# Output: My name is Alice and I'm 30 years old.
π fβstrings (Formatted Strings)
- Prefix the string with
f. - Embed expressions inside
{ }. - Any valid Python expression works:
{2 + 3},{name.upper()}.
π§ͺ Interactive Playground
Enter any text and click a method to see the result.
Result will appear here.
β¨ Challenge: Clean User Input
Write a function clean_input(text) that:
- Strips leading/trailing spaces.
- Converts to lowercase.
- Replaces multiple spaces with a single space.
- Capitalises the first letter.
def clean_input(text):
text = text.strip()
text = text.lower()
text = " ".join(text.split())
return text.capitalize()
print(clean_input(" HELLO WORLD ")) # "Hello world"
text = text.strip()
text = text.lower()
text = " ".join(text.split())
return text.capitalize()
print(clean_input(" HELLO WORLD ")) # "Hello world"
β€οΈ Support Free Education
This course is 100% free. If it helps you, consider buying me a coffee.
β Buy Me a Coffeeβ‘οΈ Ready for more?
Next lesson: Dictionaries β keyβvalue pairs.
Continue to Lesson 1.8 β(Coming soon β check back or buy Pro Pack for instant access)