Loading...
Loading...
Manipulate text with string methods and concatenation
A string (str) is Python's way of handling text. Anything inside quotes — single or double — is treated as a string. Strings can store names, sentences, entire paragraphs, or even emojis.
name = "Alice" # Double quotes
greeting = 'Hello' # Single quotes (works the same!)
empty = "" # Empty string
quote = "She said, "Hi!"" # Quotes inside quotesUse + to join strings together — this is called concatenation:
first = "John"
last = "Doe"
full = first + " " + last # Add a space in between!
print(full) # John DoeStrings come with built-in methods — actions you can perform on them:
message = "Hello, World!"
print(message.upper()) # HELLO, WORLD!
print(message.lower()) # hello, world!
print(message.title()) # Hello, World!
print(len(message)) # 13 (counts characters including spaces)
print(message.replace("World", "Python")) # Hello, Python!The cleanest way to combine text and variables — use an f before the quotes and put variables in {}:
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")
# Output: My name is Alice and I am 25 years old.Strings are everywhere in programming:
| ❌ Wrong | Why | ✅ Right |
|---|---|---|
| `name = Alice` (no quotes) | Python thinks `Alice` is a variable name | `name = "Alice"` |
| `"Hello" + 5` | Can't mix string + number | `"Hello" + str(5)` or f-strings |
| `print(len("Hello"))` | `len()` counts characters, `1` is correct actually but beginners often expect `5` | Length is 5 ✅ |
| `greeting = "hello"` then `print(Greeting)` | Capitalization matters! | `print(greeting)` |
Create a variable called city with your favorite city name. Then:
city = "Paris"
print(city.upper())
print(len(city))
print(f"My favorite city is {city}!")