Python Notes
Python strings ko deeply samjhein — creation, indexing, slicing, built-in methods, formatting, escape sequences aur real-world string manipulation ke saath complete beginners guide.
Hindi: String matlab characters ka sequence — text data. Python mein strings single quotes', double quotes", ya triple quotes"""se bana sakte hain. Yeh immutable hoti hain matlab ek baar banane ke baad change nahi hoti.
2. Creating Strings
# Single quotes
name = 'Rahul Kumar'
# Double quotes
city = "Delhi"
# Both are equivalent — use whichever is convenient
quote = 'He said "Hello!"' # single quotes to include double quotes inside
contraction = "I'm from India!" # double quotes to include apostrophe
# Triple quotes — multiline strings
address = """
123, Gandhi Nagar,
Connaught Place,
New Delhi - 110001
"""
poem = '''Roses are red,
Violets are blue,
Python is awesome,
And so are you!'''
print(name)
print(city)
print(quote)
print(contraction)
print(address)Rahul Kumar Delhi He said "Hello!" I'm from India! 123, Gandhi Nagar, Connaught Place, New Delhi - 110001 Roses are red, Violets are blue, Python is awesome, And so are you!
Special String Prefixes
# Raw string (r prefix) — backslashes treated literally
path = r"C:\Users\Rahul\Documents\notes.txt"
print(path) # prints as-is, no escape processing
# f-string (f prefix) — formatted string
name = "Priya"
greeting = f"Hello, {name}! Today is Friday."
print(greeting)
# Byte string (b prefix)
data = b"Hello in bytes"
print(data)
print(type(data))
# Unicode (u prefix — default in Python 3)
hindi = u"नमस्ते दुनिया"
print(hindi)C:\Users\Rahul\Documents\notes.txt Hello, Priya! Today is Friday. b'Hello in bytes' <class 'bytes'> नमस्ते दुनिया
3. Escape Sequences
Hindi: Escape sequences special characters hain jinhe backslash \ se likha jaata hai kyunki unhe directly type karna mushkil ya possible nahi hota.# Common escape sequences
print("Line 1\nLine 2\nLine 3") # \n — newline
print("Col1\tCol2\tCol3") # \t — tab
print("He said \"Hello!\"") # \" — double quote in string
print('It\'s Python!') # \' — single quote
print("Back\\slash") # \\ — literal backslash
print("\a") # \a — bell (alert)
# Useful for formatting
print("\033[1mBold Text\033[0m") # ANSI bold (terminal)
print("\033[91mRed Text\033[0m") # ANSI redLine 1 Line 2 Line 3 Col1 Col2 Col3 He said "Hello!" It's Python! Back\slash Bold Text Red Text
Escape Sequences Table
| Escape | Meaning | Example Output |
|---|---|---|
\n | Newline | New line |
\t | Tab | → (indent) |
\\ | Backslash | \ |
\' | Single quote | ' |
\" | Double quote | " |
\r | Carriage return | Move to line start |
\b | Backspace | Delete prev char |
\a | Bell/Alert | Beep sound |
\0 | Null character | Empty |
\xNN | Hex character | \x41 = A |
\uNNNN | Unicode | \u0928 = न |
# Unicode examples
print("\u0041") # A
print("\u0928\u092e\u0938\u094d\u0924\u0947") # नमस्ते
print("\U0001F600") # 😀 emojiA नमस्ते 😀
4. String Indexing
Hindi: String ke har character ka ek index number hota hai. Pehla character ka index 0 hota hai, negative index ka -1 se shuru hota hai.String: Python Length: 6 name[0] = 'P' name[1] = 'y' name[5] = 'n' name[-1] = 'n' name[-2] = 'o' name[-6] = 'P'
IndexError
IndexError: string index out of range TypeError: 'str' object does not support item assignment
5. String Slicing
Slicing extracts a substring using [start:stop:step] syntax.
Hindi: Slicing se string ka ek hissa nikaal sakte hain. [start:stop:step] format mein — start se shuru, stop tak (stop included NAHI), step se jump karte hue.Hello Python World! Hello Hello, Python World!
ACEGIKMO BDFHJLNP ADGJMP Reverse of 'Python' = 'nohtyP' !dlroW ,olleH
Slicing Cheat Sheet
| text[0:5] | "Hello" (chars 0,1,2,3,4) |
| text[7:] | "World!" (from 7 to end) |
| text[:5] | "Hello" (start to 4) |
| text[-6:] | "World!" (last 6 chars) |
| text[-6:-1] | "World" (last 6 to last) |
| text[::2] | "Hlo ol!" (every 2nd char) |
| text[::-1] | "!dlroW ,olleH" (reversed) |
6. String Concatenation & Repetition
Rahul Kumar Python is awesome language ======================================== HaHaHaHaHa -+--+--+--+--+--+--+--+--+--+- Hello, World!
Hindi: Baar baar+se string banana slow hota hai kyunki Python har baar naya string object banata hai.join()use karna zyada efficient hai!
7. Essential String Methods
Case Methods
text = "hello, Python WORLD!"
print(text.upper()) # ALL UPPERCASE
print(text.lower()) # all lowercase
print(text.title()) # Title Case (Each Word)
print(text.capitalize()) # First letter only
print(text.swapcase()) # sWAP eVERY cASEHELLO, PYTHON WORLD! hello, python world! Hello, Python World! Hello, python world! HELLO, pYTHON world!
Strip Methods
text = " Hello, World! "
print(f"Original: |{text}|")
print(f"strip(): |{text.strip()}|") # both sides
print(f"lstrip(): |{text.lstrip()}|") # left only
print(f"rstrip(): |{text.rstrip()}|") # right only
# Strip specific characters
dirty = "###Python###"
print(dirty.strip("#")) # Python
url = "https://example.com/"
clean = url.strip("/")
print(clean)Original: | Hello, World! | strip(): |Hello, World!| lstrip(): |Hello, World! | rstrip(): | Hello, World!| Python https://example.com
Find & Search Methods
text = "Python programming is fun and Python is powerful"
# find() — returns index, -1 if not found
print(text.find("Python")) # 0 (first occurrence)
print(text.find("Python", 1)) # 35 (search from index 1)
print(text.find("Java")) # -1 (not found)
# index() — like find() but raises ValueError if not found
print(text.index("Python")) # 0
try:
print(text.index("Java")) # ValueError
except ValueError:
print("'Java' not found!")
# count() — how many times substring appears
print(text.count("Python")) # 2
print(text.count("is")) # 2
# in operator (simplest check)
print("Python" in text) # True
print("Java" in text) # False0 35 -1 0 'Java' not found! 2 2 True False
Replace & Modify Methods
sentence = "I love Python! Python is amazing!"
# replace(old, new, count=-1)
new_sentence = sentence.replace("Python", "Java")
print(new_sentence)
# Replace only first occurrence
new_sentence = sentence.replace("Python", "Java", 1)
print(new_sentence)
# translate() — for multiple replacements
old = "aeiou"
new = "12345"
table = str.maketrans(old, new)
encoded = "hello world".translate(table)
print(encoded)I love Java! Java is amazing! I love Java! Python is amazing! h2ll4 w4rld
Split & Join Methods
['Rahul', '25', 'Delhi', 'Engineer'] Name: Rahul, Age: 25 ['one', 'two', 'three four five'] ['Line 1', 'Line 2', 'Line 3'] Python is the best Priya,22,Mumbai,Developer /home/user/documents/file.txt
Check Methods (Return Boolean)
.isdigit(): '123' → True '12.3' → False 'abc' → False '123abc' → False .isalpha(): 'Hello' → True 'Hello123' → False 'hello world' → False 'नमस्ते' → True .isalnum(): 'Hello123' → True 'Hello 123' → False 'Hello!' → False 'abc' → True ...
Start/End Methods
PDF files: ['report.pdf'] Python files: ['script.py'] Document files: ['report.pdf', 'data.csv', 'notes.txt'] Secure URLs: ['https://google.com']
8. String Formatting Deep Dive
Name: Priya Sharma Marks: 456.7 Percentage: 91.3% Name Math Sci Eng Avg ---------------------------------------- Rahul Kumar 85 92 78 85.0 Priya Sharma 92 88 95 91.7 Amit Singh 75 70 68 71.0
9. Common String Operations
Palindrome Check
'racecar ' → ✅ Palindrome 'level ' → ✅ Palindrome 'hello ' → ❌ Not palindrome 'madam ' → ✅ Palindrome 'python ' → ❌ Not palindrome 'A man a plan a canal Pana' → ✅ Palindrome 'Was it a car or a cat I s' → ✅ Palindrome
Word Frequency Counter
Word Frequency Analysis: ------------------------------ python : 4 ████ is : 4 ████ a : 2 ██ language : 1 █ easy : 1 █ to : 1 █ learn : 1 █ used : 1 █
10. String Methods Quick Reference
| Method | Description | Example |
|---|---|---|
upper() | UPPERCASE | "hi".upper() → "HI" |
lower() | lowercase | "HI".lower() → "hi" |
title() | Title Case | "hi world".title() → "Hi World" |
strip() | Remove whitespace | " hi ".strip() → "hi" |
split() | Split to list | "a,b".split(",") → ["a","b"] |
join() | List to string | ",".join(["a","b"]) → "a,b" |
replace() | Replace substring | "hi".replace("h","H") → "Hi" |
find() | Find index | "hello".find("l") → 2 |
count() | Count occurrences | "hello".count("l") → 2 |
startswith() | Check start | "hi".startswith("h") → True |
endswith() | Check end | "hi".endswith("i") → True |
isdigit() | All digits? | "123".isdigit() → True |
isalpha() | All letters? | "abc".isalpha() → True |
isalnum() | Letters & digits? | "abc1".isalnum() → True |
center() | Center in width | "hi".center(10) → " hi " |
zfill() | Zero-pad | "42".zfill(5) → "00042" |
format() | Format string | "{} {}".format("a","b") → "a b" |
11. Real-World Example: Text Processing
┌─────────────────────────────────┐ │ STUDENT INFORMATION │ ├─────────────────────────────────┤ │ Name: Rahul Kumar │ │ Age: 20 │ │ City: Delhi │ │ Marks: [85, 92, 78] │ │ Total: 255 │ │ Avg: 85.0 │ │ Grade: A │ └─────────────────────────────────┘ ┌─────────────────────────────────┐ │ STUDENT INFORMATION │ ... │ Grade: A │ └─────────────────────────────────┘
Practice Exercises
Exercise 1 — String Analysis
Given a sentence: "The Quick Brown Fox Jumps Over The Lazy Dog"
- Count total characters (with and without spaces)
- Count vowels and consonants
- List all unique words (case-insensitive)
- Reverse each word in the sentence
Exercise 2 — Password Validator
Write a function that checks if a password is strong:
- At least 8 characters
- Contains uppercase letter
- Contains lowercase letter
- Contains a digit
- Contains a special character (
!@#$%) - Returns list of what's missing
Exercise 3 — Username Generator
From full name "Anjali Priya Verma", create:
- username:
anjali_verma(first + last, lowercase) - email:
anjali.verma@wohotech.com - display:
Anjali V.(first + last initial) - initials:
A.P.V
Exercise 4 — Text Statistics
Write a function that takes any text and returns:
- Word count
- Character count
- Sentence count (ends with
.!?) - Most frequent word
- Average word length
Interview Questions
Q1. Why are Python strings immutable? What is the implication? > Strings are immutable for safety, efficiency (hashable, can be used as dict keys), and thread safety. Implication: every "modification" creates a new string object. For many string concatenations, use "".join(list) or io.StringIO instead of += for performance.
Q2. What is the difference between find() and index()? > Both find a substring's position. find() returns -1 if not found. index() raises ValueError if not found. Use find() when not finding is expected, index() when absence means something went wrong.
Q3. How does Python string slicing work? What does s[::-1] do? > Slicing: s[start:stop:step]. Defaults: start=0, stop=len(s), step=1. Negative step reverses direction. s[::-1] uses default start/stop (full string) with step -1, effectively reversing the string.
Q4. What's the most efficient way to concatenate many strings? > Use "separator".join(list_of_strings). The + operator creates a new string object each time (O(n²) total). join() calculates total length first, allocates once, then fills (O(n)). For building incrementally, use io.StringIO or a list with final join().
Q5. What is the difference between str.split() and str.split(" ")? > str.split() (no argument) splits on any whitespace (spaces, tabs, newlines) and ignores leading/trailing whitespace. str.split(" ") splits only on single spaces and includes empty strings for multiple consecutive spaces. Use no-argument split() for general word splitting.
⚠️ Common Mistakes
1. String ko directly modify karne ki koshish 🚫
Hindi: Strings immutable hain — aap kisi character ko directly change nahi kar sakte. Naya string create karna padta hai.
2. + operator se loop mein strings banana 🐌
# ❌ SLOW — har iteration mein naya string object banta hai (O(n²))
result = ""
for i in range(1000):
result += str(i) # Very slow for large loops!
# ✅ FAST — join() use karo (O(n))
result = "".join(str(i) for i in range(1000))Hindi: Loop mein+=se string build karna bahut slow hai.join()ek baar mein memory allocate karke efficiently kaam karta hai.
3. == vs is confusion for string comparison 🤔
a = "hello"
b = "hello"
print(a == b) # ✅ True — value compare
print(a is b) # ⚠️ True (interning) but unreliable!
# Long strings may NOT be interned:
x = "hello world " * 10
y = "hello world " * 10
print(x == y) # ✅ True
print(x is y) # ❌ May be False!Hindi: Strings compare karne ke liye hamesha==use karo.isidentity check hai (same object in memory) — Python kabhi intern karti hai kabhi nahi.
4. find() ka result check na karna ⚡
Hindi:find()jab substring nahi milti toh-1return karta hai. Bina check kiye use karna bugs create karega.
5. f-string mein curly braces {} bhoolna 😅
name = "Priya"
# ❌ WRONG — f prefix daalna bhool gaye
print("Hello, {name}!") # Output: Hello, {name}!
# ✅ RIGHT — f prefix lagao
print(f"Hello, {name}!") # Output: Hello, Priya!Hindi: f-string tabhi kaam karti hai jabfprefix lagaya ho. Binafke curly braces as-is print ho jayenge.
6. strip() se middle ke spaces remove karne ki koshish 🙅
text = " Hello World "
# ❌ WRONG — strip() sirf start/end ke whitespace hatata hai
print(text.strip()) # "Hello World" (beech ke spaces wahi rehte hain)
# ✅ RIGHT — beech ke extra spaces ke liye split + join use karo
print(" ".join(text.split())) # "Hello World"Hindi:strip()sirf leading/trailing whitespace remove karta hai. Middle ke spaces ke liyesplit()aurjoin()ka combo use karo.
7. Escape sequences bhoolna (especially file paths) 📁
# ❌ WRONG — \U is a unicode escape, \n is newline!
# path = "C:\Users\new_folder\test.txt" # Error or wrong output!
# ✅ RIGHT — raw string ya double backslash use karo
path = r"C:\Users\new_folder\test.txt" # raw string
path2 = "C:\\Users\\new_folder\\test.txt" # escaped backslashHindi: Windows file paths mein backslash\escape character ban jaata hai. Raw stringr"..."use karo ya double backslash\\likho.
✅ Key Takeaways
- 🔒 Strings immutable hain — ek baar create hone ke baad modify nahi ho sakti. Har "change" naya string object banata hai.
- 📍 Indexing 0 se start hoti hai aur negative indexing (
-1) end se access deti hai. Out-of-range indexIndexErrordega. - ✂️ Slicing
[start:stop:step]— stop exclusive hota hai.[::-1]se string reverse hoti hai instantly. - 🚀 f-strings (
f"...") sabse modern aur fast formatting method hai Python 3.6+ mein. Expressions directly curly braces mein likh sakte hain. - ⚡
join()method strings concatenate karne ka most efficient tarika hai, especially loops mein.+operator se avoid karo heavy operations mein. - 🔍
find()returns-1jab substring nahi milti, jabkiindex()raisesValueError— dono ka use case alag hai. - 📝
split()aurjoin()ek doosre ke opposite hain — string ↔ list conversion ke liye perfect pair hai. - 🎯 Check methods (
isdigit(),isalpha(),isupper()etc.) input validation ke liye essential hain — hamesha Boolean return karti hain. - 🛡️ Raw strings
r"..."Windows file paths aur regex patterns ke liye must-use hain, kyunki backslash ko literally treat karti hain. - 💡
inoperator sabse simple aur Pythonic way hai substring check karne ka —if "python" in text.lower():
❓ FAQ
Q1. Python mein string immutable kyon hoti hai? Iska kya fayda hai? 🔒 > Immutability ke kafi fayde hain: (1) Strings ko dictionary keys ki tarah use kar sakte hain kyunki wo hashable hain, (2) Thread-safe hain — multiple threads safely ek string share kar sakte hain, (3) Python internally string interning karke memory save karta hai. Agar strings mutable hoti toh ye sab possible nahi hota.
Q2. Single quotes '...' aur double quotes "..." mein kya difference hai? 🤷 > Functionally koi difference nahi hai! Dono same string banate hain. Use convenience ke according karo — agar string mein apostrophe hai ("I'm happy") toh double quotes use karo, agar double quote hai ('He said "Hi"') toh single quotes use karo. Triple quotes (''' ya """) multiline strings ke liye hain.
Q3. f-string, .format(), aur % formatting mein kaun sa best hai? 🏆 > f-string (recommended) — sabse readable, fastest, aur Python 3.6+ mein available hai. .format() purana method hai lekin compatible hai older Python 3.x ke saath. % formatting C-style hai aur legacy code mein milti hai. Naye code mein hamesha f-string use karo: f"Hello, {name}! Age: {age}".
Q4. strip(), lstrip(), aur rstrip() mein kya difference hai? ✂️ > strip() dono taraf (left + right) se whitespace ya specified characters hatata hai. lstrip() sirf left (start) se hatata hai. rstrip() sirf right (end) se hatata hai. Default mein whitespace (spaces, tabs, newlines) remove hota hai. Custom characters bhi pass kar sakte ho: "###hello###".strip("#") → "hello".
Q5. String mein substring check karne ke kitne tarike hain? 🔍 > Multiple tarike hain: (1) in operator: "py" in "python" → True (sabse simple), (2) find(): index return karta hai ya -1, (3) index(): index return karta hai ya ValueError raise karta hai, (4) startswith()/endswith(): beginning ya end check karne ke liye, (5) count(): kitni baar aata hai check karne ke liye. Most common aur Pythonic: in operator.
Q6. Python mein string reverse kaise karte hain? Multiple ways batao. 🔄 > Sabse popular ways: (1) Slicing: s[::-1] — fastest aur most Pythonic, (2) reversed() + join(): "".join(reversed(s)), (3) Loop: manual loop se character by character reverse karo (slow but educational). Interview mein slicing method preferred hai: "Python"[::-1] → "nohtyP".
Q7. split() bina argument ke aur split(" ") mein kya difference hai? 📋 > split() (bina argument) — any whitespace (spaces, tabs, \n) pe split karta hai, consecutive whitespace ko ek maanta hai, aur leading/trailing whitespace ignore karta hai. split(" ") — sirf single space pe split karta hai, multiple spaces pe empty strings aati hain: "a b".split(" ") → ["a", "", "b"]. General word splitting ke liye hamesha no-argument split() use karo.
Q8. String encoding (encode()/decode()) kab use karte hain? 🌐 > Jab strings ko bytes mein convert karna ho (file writing, network communication, APIs) tab encode() use hota hai: "hello".encode("utf-8") → b'hello'. Aur jab bytes ko wapas string banana ho tab decode(): b'hello'.decode("utf-8") → "hello". Web scraping, file handling, aur API responses mein frequently use hota hai. Default encoding UTF-8 hai.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Python Strings Basics.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Python Master Course topic.
Search Terms
python-master-course, python master course, python, master, course, basics, strings, python strings basics
Related Python Master Course Topics