Page4/20
Variables & Data Types · Page 4 of 5
Strings & Text Operations
Working with Strings
Strings are sequences of characters. Python gives you powerful tools to manipulate text.
String Concatenation (Joining)
Combine strings with the + operator:
first = "John"
last = "Smith"
full_name = first + " " + last # "John Smith"
F-Strings (Modern Python)
The easiest way to embed variables in text:
name = "Alice"
age = 28
score = 95.5
# F-string (readable and powerful!)
print(f"Hello {name}!") # Hello Alice!
print(f"{name} is {age} years old") # Alice is 28 years old
print(f"Score: {score:.1f}%") # Score: 95.5%
String Formatting Examples
price = 19.995
f"{price}" # "19.995"
f"{price:.2f}" # "19.99" ← 2 decimals
count = 5000
f"{count:,}" # "5,000" ← with commas
text = "hello"
f"{text.upper()}" # "HELLO" ← call methods inside!
Essential String Methods
Making changes (note: strings are immutable—these return NEW strings):
text = " Hello World "
text.lower() # " hello world "
text.upper() # " HELLO WORLD "
text.strip() # "Hello World" ← removes whitespace
text.replace("World", "Python") # " Hello Python "
Checking content:
text = "Hello"
"H" in text # True (substring check)
text.startswith("He") # True
text.endswith("lo") # True
text.isdigit() # False
" 123 ".isdigit() # False (has spaces!)
"123".isdigit() # True
Finding and splitting:
sentence = "I love Python programming"
sentence.find("Python") # 7 (position)
sentence.count("o") # 3 (occurrences)
sentence.split() # ["I", "love", "Python", "programming"]
sentence.split(" ") # same result
Important: String methods don't modify the original string—they return a new one. Strings are immutable!
main.py
Loading...
OUTPUT
▶Click "Run Code" to execute…