Chapter 8: Strings in Python
String ka matlab hota hai characters ka sequence. Ab sikhenge string methods, slicing, formatting aur manipulation.
1. String Creation
Single ya double quotes se string banate hain.
name = "Ravi"
message = 'Hello World'
2. String Indexing & Slicing
String ke characters ko access karne ke liye index ka use hota hai. Index 0 se start hota hai.
text = "Python"
print(text[0]) # Output: P
print(text[-1]) # Output: n
print(text[1:4]) # Output: yth
P
n
yth
3. String Methods
lower()
: Sab lowercase mein convert karta hai
upper()
: Sab uppercase mein convert karta hai
strip()
: Extra spaces hatata hai
replace()
: Word ko replace karta hai
split()
: String ko list mein todta hai
txt = " Hello Python "
print(txt.lower())
print(txt.strip())
print(txt.replace("Python", "World"))
print(txt.split())
" hello python "
"Hello Python"
" Hello World "
['Hello', 'Python']
4. String Concatenation
Do ya zyada strings ko jodna concatenate kehlata hai.
a = "Hello"
b = "World"
print(a + " " + b)
Hello World
5. String Formatting
Python 3 mein modern formatting f-strings ke through hoti hai.
name = "Ravi"
age = 21
print(f"My name is {name} and I am {age} years old.")
My name is Ravi and I am 21 years old.
6. Common String Mistakes
text = "Hello
print(text) # ❌ String not closed
text = "Hello"
print(text) # ✅
7. Check String
Use in
to check if substring exists:
msg = "Welcome to Python"
print("Python" in msg) # True
print("Java" not in msg) # True
8. Multiline Strings
Use triple quotes for multi-line:
para = """
This is line 1.
This is line 2.
"""
print(para)
This is line 1.
This is line 2.
9. Looping Through a String
Har character ko access karne ke liye for loop ka use hota hai.
for char in "Python":
print(char)
P
y
t
h
o
n