Strings + Text Processing
Immutability, slicing, formatting, और methods
यह क्यों मायने रखता है
ज़्यादातर interview समस्याओं में text शामिल होता है। Strings पर पकड़ समय बचाती है।
मूल विचार
Strings अपरिवर्तनीय (immutable) sequences हैं। Slicing नई strings बनाती है; आप कभी जगह पर बदलाव नहीं करते। f"" strings format करने का आधुनिक तरीक़ा हैं।
आज़माकर देखिए
Slicing — s[start:stop:step]:
s = "abcdefghij"
print(s[2:5]) # 'cde'
print(s[:4]) # 'abcd'
print(s[-3:]) # 'hij'
print(s[::2]) # 'acegi'
print(s[::-1]) # 'jihgfedcba' (reverse)
आम methods — split, strip, join, replace, find:
raw = " Hello, World, Python "
parts = [p.strip() for p in raw.split(",")]
print(parts)
print(",".join(parts))
print("python" in raw.lower())
Formatting — f-strings हर बार .format() और % को हराती हैं:
name, score = "Ada", 0.875
print(f"{name:>10} | {score:6.1%}")
print(f"{name!r:<10} | binary: {42:08b}")
# Multi-line + expressions
print(f"""
sum: {2 + 3}
list: {[i*i for i in range(5)]}
""")
String methods जो आपको ज़रूर जानने चाहिए
| श्रेणी | Methods | वे क्या करते हैं |
| --- | --- | --- |
| साफ़ करना | strip, lstrip, rstrip | whitespace हटाते हैं |
| Case | lower, upper, title, capitalize | case बदलते हैं |
| खोज | find, index, count | ढूँढते और गिनते हैं |
| मिलान | startswith, endswith | prefix/suffix जाँच |
| Split/Join | split, rsplit, splitlines, 'sep'.join(...) | tokenizing और joining |
| Replace | replace | प्रतिस्थापन |
| जाँच | isalnum, isalpha, isdigit, isnumeric, isspace | validation |
name = " Ada Lovelace "
print(name.strip().lower())
"data-science".split("-")
"-".join(["a", "b"])
Palindrome normalization pattern
एक दोबारा इस्तेमाल होने वाली विधि: केवल alphanumeric characters रखें और उन्हें lowercase करें, फिर उल्टे से तुलना करें।
def normalize(s: str) -> str:
return "".join(ch.lower() for ch in s if ch.isalnum())
झटपट जाँच
- प्र: क्या strings mutable होती हैं? उ: नहीं।
छोटे अभ्यास
- किसी string को दो तरीक़ों से उलटिए।
- किसी वाक्य में स्वर (vowels) गिनिए।
- विराम-चिह्न हटाइए और lowercase कीजिए।
क्या करें और क्या न करें
- करें तुलना से पहले
s.strip()इस्तेमाल करें। - न करें loops में
+से strings न बनाएँ।
और गहराई में — bytes बनाम str
Python 3 में text और binary अलग types हैं:
str= text (Unicode)bytes= कच्चा binary
Text से bytes तक जाने के लिए encode करें, वापस आने के लिए decode करें:
b = "hello".encode("utf-8")
text = b.decode("utf-8")आम ग़लतियाँ
- ग़लती:
s[0]को बदलने की कोशिश करना। समाधान: एक नई string बनाएँ। - ग़लती: loop में
+इस्तेमाल करना। समाधान:"".join(...)इस्तेमाल करें। - ग़लती:
findइस्तेमाल करना फिर-1न जाँचना। समाधान: परिणाम सत्यापित करें।
मुख्य बातें
- Strings अपरिवर्तनीय हैं —
s.upper()एक नई string लौटाता है,sको नहीं बदलता। - Slicing एक नई string बनाती है;
[::-1]उलटता है,[::2]हर दूसरा लेता है। - f-strings expressions और format specs समा सकती हैं (
{x:>10.2f},{x!r},{x:08b})। str.split()/"sep".join(iterable)join/split का मुहावरा है।- प्रदर्शन के लिए
.joinइस्तेमाल करें; तुलना से पहले text को सामान्य कीजिए।