Python Strings
Strings text data ko represent karti hain. Is chapter me string creation, indexing, slicing, immutability, searching, replacing, splitting, joining, cleaning, case conversion, formatting aur practical text-processing patterns samjhenge.
What is a string?
A Python string is an immutable sequence of Unicode characters. Single quotes, double quotes aur triple quotes se string literals create kiye ja sakte hain.
course = "Python"
message = 'Learn by practice'
multiline = """Line one
Line two"""
print(course)
print(message)
print(multiline)Single aur double quotes dono normal text ke liye valid hain. Triple quotes multi-line string literals ke liye useful hote hain.
Quotes and escaping
Quote style wisely choose karne se escaping kam karni padti hai.
title = "Python's Basics"
quote = 'He said "Hello"'
escaped = "He said \"Hello\""
print(title)
print(quote)
print(escaped)Escape sequences jaise \n, \t, \\ aur escaped quotes strings ke andar special characters represent karte hain.
Raw strings
Raw string prefix r most backslashes ko literal treat karne me helpful hota hai, especially regular expressions aur Windows-style paths me.
path = r"C:\Users\Student\notes"
print(path)String length with len()
len() string me characters/code points ki count return karta hai.
course = "Python"
print(len(course)) # 6Indexing
Strings zero-based indexing use karti hain. First character index 0 par hota hai.
word = "Python"
print(word[0]) # P
print(word[1]) # y
print(word[-1]) # n
print(word[-2]) # oNegative indexes end se count karte hain.
IndexError mil sakta hai.Slicing
Slicing syntax text[start:stop] start ko include aur stop ko exclude karti hai.
word = "BrounStack"
print(word[0:5])
print(word[5:])
print(word[:5])
print(word[-5:])Slice step and reverse
Third slice component step define karta hai.
text = "abcdef"
print(text[::2]) # ace
print(text[::-1]) # fedcba[::-1] common reverse-string technique hai.
Strings are immutable
String create hone ke baad individual character in-place replace nahi kiya ja sakta.
word = "python"
# word[0] = "P" # TypeError
word = "P" + word[1:]
print(word)Concatenation and repetition
first = "Broun"
second = "Stack"
brand = first + second
line = "-" * 20
print(brand)
print(line)Large-scale repeated concatenation in loops ke liye join() often more suitable hota hai.
Membership with in
title = "Learn Python Fast"
print("Python" in title)
print("Java" not in title)Membership case-sensitive hoti hai.
Case conversion methods
text = "brounstack python"
print(text.upper())
print(text.lower())
print(text.title())
print(text.capitalize())
print(text.swapcase())Case-insensitive human text comparisons me casefold() lower() se more aggressive Unicode-aware normalization provide kar sakta hai.
Remove surrounding whitespace
strip(), lstrip() aur rstrip() outer characters remove karte hain.
name = " Aman Verma "
print(name.strip())
print(name.lstrip())
print(name.rstrip())strip("ab") exact substring remove nahi karta; it removes matching characters from the ends. Exact prefix/suffix ke liye removeprefix()/removesuffix() better ho sakte hain.Prefix and suffix checks
filename = "report.pdf"
print(filename.startswith("report"))
print(filename.endswith(".pdf"))
print(filename.removesuffix(".pdf"))Search text
find() missing text par -1 return karta hai, while index() missing text par ValueError raise karta hai.
text = "Python makes text processing practical"
print(text.find("text"))
print(text.count("t"))
print("processing" in text)Simple existence check ke liye often in clearest hai.
Replace text
message = "I like Java"
updated = message.replace("Java", "Python")
print(message)
print(updated)Original string unchanged rahti hai; replace() new string return karta hai.
Split a string
split() string ko pieces ki list me divide karta hai.
skills = "HTML,CSS,JavaScript,Python"
parts = skills.split(",")
print(parts)
print(parts[0])Whitespace-based split ke liye text.split() without argument repeated whitespace ko conveniently handle karta hai.
Join strings
separator.join(iterable) multiple strings ko efficiently combine karta hai.
skills = ["HTML", "CSS", "Python"]
result = " | ".join(skills)
print(result)join() ko string elements chahiye. Numbers ko pehle string me convert karna pad sakta hai.partition() for three parts
partition() first separator occurrence par exactly three-part tuple return karta hai.
email = "student@example.com"
name, separator, domain = email.partition("@")
print(name)
print(domain)Useful validation methods
print("123".isdigit())
print("Python".isalpha())
print("Python3".isalnum())
print(" ".isspace())
print("hello".islower())
print("HELLO".isupper())Ye methods input validation me useful signals de sakti hain, but real validation rules usually business context par depend karte hain.
f-strings revisited
Variables, expressions aur formatting ko readable output me combine karne ke liye f-strings useful hain.
name = "Aman"
score = 91.456
print(f"{name} scored {score:.2f}%")
print(f"Name length: {len(name)}")Unicode basics
Python str Unicode text handle karta hai, so Hindi, emojis aur many world scripts directly strings me use kiye ja sakte hain.
greeting = "नमस्ते"
emoji = "🚀"
print(greeting)
print(emoji)str vs bytes preview
str text hai; bytes raw byte data. Encoding text ko bytes me aur decoding bytes ko text me convert karti hai.
text = "Python"
data = text.encode("utf-8")
restored = data.decode("utf-8")
print(data)
print(restored)Files, HTTP aur APIs me encoding later practical importance rakhegi.
Loop through a string
word = "Python"
for character in word:
print(character)Strings iterable hain, isliye for loop directly characters par iterate kar sakta hai.
Practical text-cleaning pattern
raw_name = " aMaN verMA "
clean_name = raw_name.strip().title()
print(clean_name)Method chaining concise ho sakti hai, but excessively long chains readability reduce kar sakti hain.
Performance note
Strings immutable hone ki wajah se repeated result += piece in very large loops unnecessary intermediate strings create kar sakta hai. Multiple pieces ko list me collect karke "".join(parts) often clearer and efficient pattern hai.
Common beginner mistakes
- String index ko 1 se start assume karna.
- Slice stop index ko inclusive samajhna.
- Out-of-range direct indexing karna.
- String character ko in-place assign karna.
- String methods call karke returned value ignore karna while expecting original string to change.
find()aurindex()behavior mix karna.strip(chars)ko exact substring removal samajhna.- Case-sensitive comparison ko accidentally case-insensitive expect karna.
join()me integers directly dena.- Escaping/raw-string rules samjhe bina paths create karna.
- Input normalization me password jaisi sensitive values ko unnecessarily modify karna.
Beginner best practices
- User text ko context ke according
strip()karo. - Exact prefix/suffix operations ke liye dedicated methods use karo.
- Existence check ke liye readable
inprefer karo. - Formatting ke liye f-strings use karo.
- Multiple strings combine karne ke liye suitable jagah
join()use karo. - Case normalization tabhi karo jab domain rules allow karte hon.
- Original text preserve karna important ho to cleaned version separate variable me rakho.
- Unicode text ko normal Python strings me safely handle karo; bytes conversion only when needed.
Chapter checklist
- String creation aur quote styles clear hain?
- Positive/negative indexing use kar sakte ho?
- Slicing ka start/stop/step pattern samajh aaya?
- String immutability clear hai?
strip(),replace(),split()aurjoin()use kar sakte ho?find()vsinka difference clear hai?- Validation methods aur f-strings use kar sakte ho?
strvsbyteska basic idea samajh aaya?
Practice Task — Text Profile Cleaner
BrounStack Playground me user profile text clean aur analyze karne wala program banao.
- Full name input lo.
- Email input lo.
- Comma-separated skills input lo.
- Name par
strip()use karo. - Name ko readable case me convert karo.
- Email ko surrounding whitespace se clean karo.
- Email me
@present hai ya nahi check karo. partition("@")se local part aur domain nikalo.- Skills ko comma par
split()karo. - Har skill ko clean karne ke liye loop use karo.
- Clean skills ko
" | ".join(...)se combine karo. - Name length print karo.
- Email domain print karo.
- Final profile f-string se display karo.
- Empty ya messy spaces ke saath different inputs test karo.