Lesson 10 of 4025%
(Progress persistence is disabled until Phase 9)
Python
Beginner
Strings
Master text manipulation with Python's string features.
Strings
What You’ll Learn
Strings are used to store text. You’ll learn how to format, slice, and use methods on strings.
Creating Strings
Strings can be surrounded by either single quotation marks or double quotation marks.
word1 = 'hello'
word2 = "hello" # This is exactly the same
F-Strings (Formatted String Literals)
F-strings are the most modern and preferred way to format strings in Python. Just prefix the string with f and use curly braces {} to inject variables.
name = "Usman"
age = 20
# The f goes right before the quote
greeting = f"My name is {name} and I am {age} years old."
print(greeting)
String Length
Use the len() function to find the length of a string.
text = "BrowserCode"
print(len(text)) # Output: 11
Useful String Methods
Strings come with many built-in methods. Methods are functions that belong to an object, accessed using a dot ..
text = " Hello, World! "
print(text.upper()) # " HELLO, WORLD! "
print(text.lower()) # " hello, world! "
print(text.strip()) # "Hello, World!" (removes whitespace at start/end)
print(text.replace("H", "J")) # " Jello, World! "
Common Mistakes
- Concatenating strings and numbers: You cannot use
+to add a string and a number."Age: " + 20will fail. Use f-strings instead:f"Age: {20}".