Strings
5 min read Quiz at the end
Strings are text in quotes. Use f-strings for easy formatting: f'Hello {name}'. Key methods: upper(), lower(), strip(), split(), join(), and replace(). Strings are immutable — methods always return new strings.
String Operations s = "Hello, Python!"
print(len(s)) # 14
print(s.upper()) # HELLO, PYTHON!
print(s.lower())
print(s.replace("Python", "World"))
print(s[0:5]) # Hello
print(s.split(",")) # ['Hello', ' Python!']
# f-strings (best practice)
name = "Alice"
print(f"Hi, {name}!") # Hi, Alice!
Topic Quiz · 5 questions
Test your understanding before moving on
1. Which is the best way to format strings in Python 3.6+?
A. %s formatting
B. str.format()
C. f-strings
D. + concatenation
💡 f-strings (f"Hello {name}") are the most readable and efficient string formatting.
2. Which method converts a string to uppercase?
A. .up()
B. .toUpper()
C. .upper()
D. .capitalize()
💡 .upper() converts all characters to uppercase.
3. How do you get the length of a string?
A. str.length()
B. count(str)
C. len(str)
D. str.size()
💡 len() returns the length of a string (and other sequences).
4. What does "hello"[1:4] return?
A. hell
B. ell
C. ello
D. hel
💡 Slicing [1:4] returns characters at indices 1, 2, 3 → "ell".
5. Which method splits a string by a delimiter?
A. .split()
B. .divide()
C. .break()
D. .tokenize()
💡 .split(delimiter) splits a string into a list.
Submit answers