📝 Python में String Handling – Methods और Examples के साथ [2025 Updated]

Python में String एक sequence of characters होती है जिसका इस्तेमाल हम text data को store और manipulate करने के लिए करते हैं। इस गाइड में हम Python String in Hindi को आसान भाषा और practical examples के साथ समझेंगे, जिसमें string creation, common methods और real-life use cases शामिल हैं।

✍️ String बनाना

Python में single (‘ ‘), double (” “) या triple quotes (”’ ”’) का इस्तेमाल कर string बनाई जाती है। Example: name = "Vista Academy"

🛠 Common String Methods

Methods जैसे .upper(), .lower(), .replace() text को format और modify करने के लिए इस्तेमाल होते हैं।

💡 Real-Life Use Cases

String का इस्तेमाल usernames validate करने, text cleaning, और data parsing में होता है। Example: "hello".capitalize() → “Hello”

🔤 Python String Basics (in Hindi) — Quick Reference + Examples

इस सेक्शन में python string in hindi के core concepts को एक नज़र में समझें—creation, indexing/slicing, formatting और सबसे ज़्यादा इस्तेमाल होने वाले methods।

Topic Syntax Example Notes
Create '..', "..", '''...''' name = "Vista Academy" Triple quotes = multi-line
Length len(s) len("hello") → 5 Spaces counted
Indexing s[i] "hello"[1] → 'e' 0-based index
Slicing s[start:stop:step] "python"[1:4] → 'yth' Negatives allowed: s[::-1]
Concat a + b "Py" + "thon" Costly in loops → use .join
Repeat s * n "ha" * 3 → "hahaha" Fast
Escape "He said \"Hi\"" 'It\'s ok' Raw strings: r'..\n..'
f-Strings f"Hi {name}" f"{pi:.2f}" → '3.14' Best for formatting
🧱 Strings are Immutable 🧩 Use split, join for text ⚡ Prefer f"" over %/.format
Example 1: Create, Index, Slice
text = "Vista Academy"
print(len(text))       # 13
print(text[0], text[-1])  # V y
print(text[6:14])      # 'Academy'
print(text[::-1])      # Reverse
Example 2: Common String Methods
s = "  hello, world!  "
print(s.upper())          # '  HELLO, WORLD!  '
print(s.strip())          # 'hello, world!'
print(s.replace("world","Python"))  # '  hello, Python!  '
print(s.split(","))       # ['  hello', ' world!  ']
print(" | ".join(["A","B","C"]))  # 'A | B | C'
print(s.find("world"))    # 9 (index or -1)
Example 3: Validation (isalpha, isnumeric, startswith)
u = "User123"
print(u.isalpha())        # False
print("12345".isnumeric())# True
print("user@example.com".startswith("user"))  # True
print("readme.md".endswith(".md"))           # True
Example 4: f-Strings (Formatting)
name = "Vista"
price = 249.9
msg = f"Hello {name}, total = ₹{price:.2f}"
print(msg)  # Hello Vista, total = ₹249.90
Example 5: Immutability, Join vs +
# Inefficient in loop
parts = []
for i in range(3):
    parts.append(str(i))
print("".join(parts))  # '012'

🧰 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() उपयोगी है।

Vista Academy – 316/336, Park Rd, Laxman Chowk, Dehradun – 248001
📞 +91 94117 78145 | 📧 thevistaacademy@gmail.com | 💬 WhatsApp
💬 Chat on WhatsApp: Ask About Our Courses