Data Structures · #5 / 11

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)
not loaded

आम 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())
not loaded

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)]}
""")
not loaded

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())

झटपट जाँच

छोटे अभ्यास

क्या करें और क्या न करें

और गहराई में — 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")

आम ग़लतियाँ

मुख्य बातें