🐍 Lesson 9: Python Strings
1. What is a string?
Short answer → A string is a data type that stores letters, sentences, and text.
In other words → A string is a sequence of characters enclosed in quotes.
2. Commonly Used String Methods
upper()→ converts to uppercaselower()→ converts to lowercasestrip()→ removes leading and trailing spacesreplace(a, b)→ replaces a with bsplit()→ splits a sentence into a list
3. String Formatting
If you want to insert variables into a string, f-string makes it easy
4. Summary
✅ String = a text data type
✅ You can access characters using indexing and slicing
✅ Commonly used methods include upper, lower, strip, replace, and split
✅ Use f-strings to combine text with variables
python
# ===== 1. String Creation =====
a = 'Hello'
b = "World"
c = """This is
a multi-line
string"""
print(f"Single quotes: {a}")
print(f"Double quotes: {b}")
print(f"Multi-line: {c}")
# ===== 2. String Indexing & Slicing =====
print(f"\n===== Indexing & Slicing =====")
text = "Python"
print(f"First character: {text[0]}") # P
print(f"Last character: {text[-1]}") # n
print(f"Slice [0:3]: {text[0:3]}") # Pyt
print(f"Slice [2:]: {text[2:]}") # thon
# ===== 3. String Methods =====
print(f"\n===== String Methods =====")
txt = " hello world "
print(f"Upper: {txt.upper()}")
print(f"Lower: {txt.lower()}")
print(f"Strip: '{txt.strip()}'")
print(f"Replace: {txt.replace('world', 'Python')}")
print(f"Split: {txt.split()}")
# ===== 4. String Formatting (f-strings) =====
print(f"\n===== String Formatting =====")
name = "Sai"
age = 25
print(f"My name is {name}, I am {age} years old.")
# ===== 5. String Length =====
print(f"\nLength of 'Python': {len('Python')}")You should see
Single quotes: Hello Double quotes: World Multi-line: This is a multi-line string ===== Indexing & Slicing ===== First character: P Last character: n Slice [0:3]: Pyt Slice [2:]: thon ===== String Methods ===== Upper: HELLO WORLD Lower: hello world Strip: 'hello world' Replace: hello Python Split: ['hello', 'world'] ===== String Formatting ===== My name is Sai, I am 25 years old. Length of 'Python': 6