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)