▶️ आगे: Top 20 String Methods (with mini demos)

🧰 Top 20 String Methods in Python (in Hindi) — Quick Mini Demos

इस सेक्शन में हम python string in hindi के 20 ज़रूरी methods को छोटे-छोटे examples के साथ समझेंगे। Copy-बटन से सीधे कोड उठाएँ और चलाएँ।

Case Methods: upper, lower, title, capitalize
s = "hello world"
print(s.upper())      # HELLO WORLD
print(s.lower())      # hello world
print(s.title())      # Hello World
print(s.capitalize()) # Hello world
strip, lstrip, rstrip
s = "  **hello**  "
print(s.strip())       # '**hello**'
print(s.strip(" *"))   # 'hello'
print(s.lstrip())      # '**hello**  '
print(s.rstrip())      # '  **hello**'
replace
text = "2024-12-31"
print(text.replace("-", "/"))      # 2024/12/31
print("aaaa".replace("a","A",2))   # AAaa (count=2)
split, rsplit, splitlines
"a,b,c".split(",")        # ['a','b','c']
"a,b,c".rsplit(",", 1)     # ['a,b','c']
"line1\nline2".splitlines()# ['line1','line2']
join
items = ["A","B","C"]
print(" | ".join(items))  # A | B | C
find, rfind, index, rindex
s = "abracadabra"
print(s.find("bra"))   # 1  (or -1)
print(s.rfind("bra"))  # 8
print(s.index("cad"))  # 4  (ValueError if not found)
count
s = "banana"
print(s.count("an"))    # 2
print(s.count("a", 1))  # from index 1 → 2
startswith, endswith
print("hello.py".endswith(".py")) # True
print("Mr. John".startswith("Mr")) # True
zfill, rjust, ljust, center
print("42".zfill(5))          # 00042
print("hi".rjust(5,"-"))       # ---hi
print("hi".ljust(5,"-"))       # hi---
print("hi".center(6,"*"))      # **hi**
partition, rpartition
s = "key=value=extra"
print(s.partition("="))   # ('key', '=', 'value=extra')
print(s.rpartition("="))  # ('key=value', '=', 'extra')
isalpha, isdigit, isnumeric, isalnum, isspace
print("ABC".isalpha())     # True
print("123".isdigit())      # True
print("१२३".isnumeric())    # True (Devanagari)
print("A1".isalnum())       # True
print("  ".isspace())       # True
casefold (Unicode-insensitive lower)
# बेहतर lower() वैरिएंट: Unicode friendly
print("Straße".lower() == "strasse")    # False
print("Straße".casefold() == "strasse") # True
encode / decode (UTF-8)
data = "नमस्ते"
b = data.encode("utf-8")   # bytes
print(type(b), b)
print(b.decode("utf-8"))   # back to str
translate + maketrans
tbl = str.maketrans({"a":"@", "e":"3"})
print("peace".translate(tbl)) # p3@c3
format vs f-strings
name, price = "Vista", 249.9
print("Hello {}, ₹{:.2f}".format(name, price))
print(f"Hello {name}, ₹{price:.2f}")  # preferred
swapcase
print("PyThOn".swapcase())  # pYtHoN
expandtabs
print("a\tb\tc".expandtabs(4))  # tab → 4 spaces
startswith/endswith with tuple
fn = "report.xlsx"
print(fn.endswith((".xlsx",".csv")))  # True
Sanitize: replace + count
txt = "Spam!!! Buy!!!"
clean = txt.replace("!", "")
print(clean, "removed:", txt.count("!"))
Bonus: slicing tricks
s = "0123456789"
print(s[::-1])   # reverse
print(s[::2])    # step 2 → 02468
print(s[-4:])    # last 4 → 6789

🧪 10 Practice Problems — String Cleaning, Validation & Formatting

इन problems से आपकी python string in hindi समझ practically मजबूत होगी—cleaning, validation, formatting, parsing और छोटे-छोटे real-world tasks पर ध्यान।

P1. Basic Email Check

जाँचें कि string में ‘@’ और ‘.’ मौजूद हैं (very basic).

💡 Hint

‘@’ in s and ‘.’ in s

✅ Solution
s = "user@example.com"
is_basic_email = ("@" in s) and ("." in s)
print(is_basic_email)

P2. Username Normalize

lower + trim spaces + internal spaces को single ‘-‘ में बदलें।

💡 Hint

s.strip().lower().split()

✅ Solution
raw = "  Vista   Academy  "
norm = "-".join(raw.strip().lower().split())
print(norm)  # vista-academy

P3. Proper Name Title Case

name को clean करके Title Case में बदलें।

💡 Hint

strip + lower + title()

✅ Solution
name = "   viSTA   aCAdemy "
clean = name.strip().lower().title()
print(clean)  # 'Vista Academy'

P4. Count Vowels

string में vowels की गिनती करें (a, e, i, o, u).

💡 Hint

sum(ch in ‘aeiou’)

✅ Solution
txt = "Data Science"
v = sum(ch.lower() in "aeiou" for ch in txt)
print(v)

P5. Remove Punctuation

text से !?,.:- जैसे punctuation हटाएँ।

💡 Hint

translate + maketrans

✅ Solution
punc = "!?.,:-;\"'"
table = str.maketrans("", "", punc)
print("Hello, World!!!".translate(table))  # Hello World

P6. Extract Digits & Sum

string में मौजूद digits का sum निकालें (char-wise).

💡 Hint

ch.isdigit()

✅ Solution
s = "a1b2c3"
total = sum(int(ch) for ch in s if ch.isdigit())
print(total)  # 6

P7. Mask Phone Number

“9876543210” → “******3210”

💡 Hint

s[-4:] + ‘*’ * (len(s)-4) (order ठीक रखें)

✅ Solution
ph = "9876543210"
masked = "*" * (len(ph) - 4) + ph[-4:]
print(masked)

P8. URL Slug (Simple)

Title → kebab-case slug (letters/digits/hyphen).

💡 Hint

lower + replace spaces → ‘-‘ + regex non-alnum drop

✅ Solution
import re
title = "Python String in Hindi — Best Guide!"
s = title.lower().strip().replace(" ", "-")
s = re.sub(r"[^a-z0-9\-]+", "", s)
s = re.sub(r"-+", "-", s).strip("-")
print(s)

P9. Most Frequent Character

spaces ignore करें, lowercase में count करके top char बताएं।

💡 Hint

max(set(s), key=s.count)

✅ Solution
txt = "Better Data Better World"
clean = txt.replace(" ", "").lower()
top = max(set(clean), key=clean.count)
print(top)

P10. Palindrome Check (alnum only)

non-alphanumeric हटाकर palindrome जाँचें।

💡 Hint

filter(str.isalnum, s.lower())[::-1]

✅ Solution
s = "A man, a plan, a canal: Panama!"
clean = "".join(ch for ch in s.lower() if ch.isalnum())
print(clean == clean[::-1])

❓ Python String — FAQ (Hindi, 2025 Updated)

Python में String क्या होती है? (python string in hindi)

String characters का ordered sequence है, जैसे "Hello" या 'नमस्ते'। यह immutable होती है—बदलने पर नया object बनता है।

String कैसे बनती है? Single, Double, Triple quotes का फर्क?

Single ('..') और Double ("..") एक जैसे हैं; Triple quotes (''' ... ''' या """ ... """) multi-line strings के लिए उपयोग करें।

String में indexing और slicing कैसे करते हैं?

Indexing: s[i] (0-based). Slicing: s[start:stop:step]. उदाहरण: "python"[1:4]'yth', "abc"[::-1]'cba'.

Common string methods कौन-सी हैं?

upper(), lower(), strip(), replace(), split(), join(), find(), startswith(), endswith(), count() आदि—ऊपर दिए गए demos देखें।

String formatting के लिए f-strings क्यों बेहतर हैं?

f-strings readable और fast होती हैं: f"Total: ₹{price:.2f}". यह .format() या % से concise और modern है।

Unicode/इमोजी के साथ Strings कैसे handle करें?

Python 3 में strings Unicode हैं—UTF-8 encode/decode करें: s.encode("utf-8") और b.decode("utf-8"). Case-insensitive compare के लिए casefold() उपयोगी है।

```html
📋 Get Course Details
```