The Story That Explains Strings 📿Strings समझाने वाली कहानी 📿一个解释字符串的故事 📿
But here is the catch: this is a museum piece. You are not allowed to change a bead once it is on the string. If you want to change 'H' to 'J' and get "JELLO", you must make a brand-new string. The original "HELLO" stays untouched.
That is exactly how Python strings work. They are sequences of characters that you can inspect, slice and combine — but never change in place. This property is called immutability, and it is one of the most important design decisions in Python.
पर एक शर्त है: यह संग्रहालय की चीज़ है। धागे पर लगे मोती को बदलने की इजाज़त नहीं। अगर 'H' को 'J' करके "JELLO" चाहिए, तो एक बिल्कुल नई माला बनानी होगी। असली "HELLO" जैसी थी वैसी रहती है।
Python strings ठीक ऐसे ही काम करती हैं। वे characters का क्रम (sequence) हैं जिन्हें आप देख, काट (slice) और जोड़ सकते हैं — पर अपनी जगह पर कभी बदल नहीं सकते। इस गुण को immutability कहते हैं, और यह Python के सबसे अहम design फ़ैसलों में से एक है।
但有一个限制:这是一件博物馆展品。珠子一旦串上,就不允许更换。如果想把 'H' 换成 'J' 得到 "JELLO",你必须做一串全新的。原来的 "HELLO" 保持不变。
Python 的字符串正是这样工作的。它们是字符序列,可以查看、切片、拼接 —— 但永远不能原地修改。这个特性叫做不可变性(immutability),是 Python 最重要的设计决定之一。
Blue numbers count from the left (0, 1, 2…). Purple numbers count from the right (-1 is the last bead).
नीले अंक बाएँ से गिनते हैं (0, 1, 2…)। बैंगनी अंक दाएँ से गिनते हैं (-1 आख़िरी मोती है)।
蓝色数字从左数(0、1、2……),紫色数字从右数(-1 是最后一颗)。
A string (str) is a sequence of characters inside quotes. Strings hold all text in Python — names, messages, file names, URLs, JSON, HTML. It is the data type you will use most often in real programs.
String (str) quotes के अंदर लिखा characters का क्रम है। Python में सारा text strings में रहता है — नाम, संदेश, file के नाम, URLs, JSON, HTML। असली programs में यही data type आप सबसे ज़्यादा इस्तेमाल करेंगे।
字符串(str)是放在引号里的字符序列。Python 中所有文本都用字符串表示 —— 名字、消息、文件名、URL、JSON、HTML。它是真实程序中你最常用的数据类型。
1. A string is a sequence — an ordered row of characters, each at a numbered position (an index). That is why indexing and slicing work.
2. A string is immutable — once created, its contents cannot change. Every "change" makes a brand-new string.
1. String एक sequence है — characters की क्रमबद्ध पंक्ति, हर एक अपनी गिनती वाली जगह (index) पर। इसीलिए indexing और slicing काम करते हैं।
2. String immutable है — बनने के बाद उसकी सामग्री नहीं बदल सकती। हर "बदलाव" एक बिल्कुल नई string बनाता है।
1. 字符串是一个序列 —— 一排有序的字符,每个字符都在一个编号位置(索引)上。这就是索引和切片能工作的原因。
2. 字符串是不可变的 —— 创建后内容不能改变。每次“修改”都会产生一个全新的字符串。
Creating Strings — Four Ways ✍️Strings बनाना — चार तरीक़े ✍️创建字符串 —— 四种方式 ✍️
Python gives you four ways to write a string. Each has a job. Knowing which to pick is the first sign of a fluent Python programmer.
Python string लिखने के चार तरीक़े देता है। हर एक का अपना काम है। कौन सा चुनना है, यह जानना Python में माहिर होने की पहली निशानी है।
Python 提供四种方式来书写字符串,各有用途。知道何时用哪种,是熟练 Python 程序员的第一个标志。
name = 'Asha'
quote = 'She said "Python is fun"' # double quotes inside — no escaping
message = "Hello, World!"
apostrophe = "it's a wonderful day" # apostrophe inside — no escaping
poem = """Roses are red,
Violets are blue,
Python is awesome,
And so are you."""
def greet(name):
"""Return a greeting for the given name.""" # a docstring
return f"Hello, {name}!"
windows_path = r"C:\Users\Asha\new_folder" # raw string: backslashes stay
regex_pattern = r"\d+\.\d+"
print(name, message)
print(quote, "|", apostrophe)
print(poem)
print(windows_path, regex_pattern)
print(repr(""), len(""), bool("")) # the empty string is real, and falsy
"" and '' are both valid strings with zero characters. The last line above shows it: length 0, and bool("") is False. That is why if my_string: is the Pythonic way to check "not empty".
"" और '' दोनों शून्य characters वाली सही strings हैं। ऊपर की आख़िरी line यही दिखाती है: length 0, और bool("") False है। इसीलिए "ख़ाली नहीं है" जाँचने का Pythonic तरीक़ा if my_string: है।
"" 和 '' 都是零个字符的合法字符串。上面最后一行正说明了这点:长度为 0,且 bool("") 为 False。所以检查“非空”的 Pythonic 写法是 if my_string:。
Immutability — What It Really Means 🔒Immutability — असल में इसका मतलब 🔒不可变性 —— 真正的含义 🔒
Python strings are printed books. Once created, the characters inside never change. Any operation that seems to "change" a string really creates a new string and leaves the original alone.
Python strings छपी किताबें हैं। बनने के बाद उनके अंदर के characters कभी नहीं बदलते। जो भी काम string को "बदलता" लगता है, वह असल में नई string बनाता है और असली को छोड़ देता है।
Python 字符串就是印好的书。一旦创建,里面的字符永远不会改变。任何看起来“修改”字符串的操作,实际上都是创建一个新字符串,原字符串保持不变。
Immutability has a precise meaning: the object's data cannot change after it is created. You can still point the variable name at a different string. That only moves the label to a new object. The old string is unchanged, and Python frees it when nothing uses it any more.
Immutability का एक सटीक मतलब है: बनने के बाद object का data नहीं बदल सकता। आप variable का नाम अब भी किसी दूसरी string की ओर कर सकते हैं। इससे सिर्फ़ label नए object पर जाता है। पुरानी string वैसी ही रहती है, और जब कोई उसे इस्तेमाल नहीं करता तो Python उसे मुक्त कर देता है।
不可变性有精确的含义:对象创建后,其数据不能改变。你仍然可以让变量名指向另一个字符串,这只是把标签挪到了新对象上。旧字符串保持不变,没有任何东西再使用它时,Python 会释放它。
Immutability in Action — See It for YourselfImmutability काम करते हुए — ख़ुद देखिए不可变性实战 —— 亲眼看看
word = "Python"
try:
word[0] = "J"
except TypeError as err:
print("TypeError:", err)
original = "hello"
uppercase = original.upper()
print(original, uppercase)
print(original is uppercase) # two different objects
name = "Asha"
first = id(name)
name = name + " Verma" # looks like a change…
print(name, id(name) == first) # …but it is a new object
The label name moves to a new object. The old 'Asha' is never edited.
Label name नए object पर चला जाता है। पुराना 'Asha' कभी बदला नहीं जाता।
标签 name 移到了新对象上,旧的 'Asha' 从未被修改。
We compare id() values and print True or False instead of printing raw addresses. The numbers change on every run and every computer, but the comparison result is always the same.
हम कच्चे addresses छापने की जगह id() की तुलना करके True या False छापते हैं। अंक हर run और हर computer पर बदलते हैं, पर तुलना का नतीजा हमेशा एक जैसा रहता है।
我们比较 id() 的值并打印 True 或 False,而不是打印原始地址。这些数字每次运行、每台电脑都不同,但比较结果始终一致。
Mutable vs Immutable — Side by SideMutable बनाम Immutable — आमने-सामने可变 vs 不可变 —— 并排对比
| Propertyगुण特性 | Behaviourव्यवहार行为 |
|---|---|
| Change in placeअपनी जगह बदलाव原地修改 | Yes, allowedहाँ, संभव可以 |
| A change givesबदलाव से मिलता है修改的结果 | Same object, new contentवही object, नई सामग्री同一对象,新内容 |
| id() after a changeबदलाव के बाद id()修改后的 id() | Sameवही不变 |
| Can be a dict key?Dict key बन सकता है?能作字典键? | No (unhashable)नहीं (unhashable)不能(不可哈希) |
| Shared between threadsThreads में साझा多线程共享 | Needs care (locks)सावधानी चाहिए (locks)需要小心(加锁) |
| Exampleउदाहरण示例 | lst.append(1) — no new listकोई नई list नहीं不产生新列表 |
| Propertyगुण特性 | Behaviourव्यवहार行为 |
|---|---|
| Change in placeअपनी जगह बदलाव原地修改 | Impossibleअसंभव不可能 |
| A change givesबदलाव से मिलता है修改的结果 | A new objectएक नया object一个新对象 |
| id() after a changeबदलाव के बाद id()修改后的 id() | Different (new object)अलग (नया object)不同(新对象) |
| Can be a dict key?Dict key बन सकता है?能作字典键? | Yes*हाँ*能* |
| Shared between threadsThreads में साझा多线程共享 | Safe to readपढ़ना सुरक्षित读取安全 |
| Exampleउदाहरण示例 | s + "!" → new stringनई string新字符串 |
* A tuple is hashable only if everything inside it is hashable. (1, "a") works as a key; (1, [2]) does not.
* Tuple तभी hashable है जब उसके अंदर का सब कुछ hashable हो। (1, "a") key बन सकता है; (1, [2]) नहीं।
* 只有当元组里的所有元素都可哈希时,元组才可哈希。(1, "a") 能作键;(1, [2]) 不能。
Why Immutability Exists — The Design Reasons 🧠Immutability क्यों है — Design के कारण 🧠为什么要不可变 —— 设计原因 🧠
This was not an accident. Python's designers made strings immutable on purpose. Here are four strong reasons. Knowing them helps you decide when to use a string and when to use a list.
यह संयोग नहीं था। Python के designers ने strings को जान-बूझकर immutable बनाया। इसके चार मज़बूत कारण हैं। इन्हें जानकर आप तय कर पाएँगे कि कब string लगानी है और कब list।
这不是偶然。Python 的设计者有意让字符串不可变,背后有四个有力的理由。了解它们能帮你判断什么时候用字符串、什么时候用列表。
Proof: Interning and Hashingसबूत: Interning और Hashing证明:驻留与哈希
a = "hello"
b = "hello"
print(a is b) # True: identifier-like literals are interned
c = "hello world"
d = "".join(["hello", " world"]) # built at run time
print(c == d, c is d) # equal text, different objects — always compare with ==
user_ages = {"asha": 30, "ravi": 25, "meena": 35}
print(user_ages["asha"]) # strings work as dict keys: they are hashable
print(hash("asha") == hash("as" + "ha"))
try:
bad = {[1, 2, 3]: "value"}
except TypeError as err:
print("TypeError:", err)
a is b was True for "hello", but c is d was False for two equal copies of "hello world" built at run time. Interning is a CPython detail, not a promise. Use == to compare string values — always.
"hello" के लिए a is b True था, पर run time पर बनी "hello world" की दो बराबर copies के लिए c is d False था। Interning CPython का अंदरूनी तरीक़ा है, वादा नहीं। String के मान की तुलना के लिए हमेशा == लगाएँ।
对 "hello" 来说 a is b 为 True,但对运行时构造的两个相等的 "hello world",c is d 为 False。驻留是 CPython 的实现细节,不是保证。比较字符串的值,永远用 ==。
Immutability costs a little extra work (a new string for each change), but brings big wins in speed, safety and predictability. Text is read far more often than it is changed, so the deal is worth it. Java, C#, JavaScript and Go also have immutable strings. (Not every language agrees: C++, Ruby and Swift let you change a string in place.)
Immutability में थोड़ा अतिरिक्त काम लगता है (हर बदलाव पर नई string), पर गति, सुरक्षा और भरोसे में बड़े फ़ायदे मिलते हैं। Text बदला कम और पढ़ा ज़्यादा जाता है, इसलिए यह सौदा फ़ायदेमंद है। Java, C#, JavaScript और Go में भी strings immutable हैं। (हर भाषा सहमत नहीं: C++, Ruby और Swift में string अपनी जगह बदली जा सकती है।)
不可变性会多花一点功夫(每次修改都产生新字符串),但在速度、安全和可预测性上收获巨大。文本被读取的次数远多于被修改的次数,所以这笔交易很划算。Java、C#、JavaScript 和 Go 的字符串也是不可变的。(并非所有语言都这样:C++、Ruby 和 Swift 允许原地修改字符串。)
String Indexing — Reading One Character 🔍String Indexing — एक Character पढ़ना 🔍字符串索引 —— 读取单个字符 🔍
A string is a sequence, so every character has a position number (index). Python counts from zero: the first character is at index 0, not 1. You can also use negative indexes to count backwards from the end.
String एक sequence है, इसलिए हर character का एक स्थान-अंक (index) है। Python शून्य से गिनता है: पहला character index 0 पर है, 1 पर नहीं। आप अंत से उल्टा गिनने के लिए negative indexes भी लगा सकते हैं।
字符串是序列,所以每个字符都有一个位置编号(索引)。Python 从零开始数:第一个字符在索引 0,而不是 1。你也可以用负索引从末尾倒着数。
word = "PYTHON"
print(word[0], word[1], word[5])
print(word[-1], word[-2], word[-6])
print(len(word))
name = "Alexander"
print(f"{name} starts with '{name[0]}' and ends with '{name[-1]}'")
try:
word[10]
except IndexError as err:
print("IndexError:", err)
In C or Java, the last character needs word[word.length - 1] — long and easy to get wrong. In Python, word[-1] just works. Use negative indexes freely; they match how people think ("the second to last item").
C या Java में आख़िरी character के लिए word[word.length - 1] लिखना पड़ता है — लंबा और ग़लती वाला। Python में word[-1] सीधे काम करता है। Negative indexes खुलकर लगाएँ; वे लोगों के सोचने के तरीक़े से मेल खाते हैं ("आख़िरी से दूसरा item")।
在 C 或 Java 中,取最后一个字符要写 word[word.length - 1] —— 又长又容易错。在 Python 中,word[-1] 直接就行。大胆使用负索引,它符合人的思维方式(“倒数第二个”)。
String Slicing — Taking a Piece ✂️String Slicing — एक टुकड़ा लेना ✂️字符串切片 —— 取出一段 ✂️
Slicing takes a part of a string. The syntax is s[start:stop:step]. All three parts are optional, so you get a lot of power from very little code.
Slicing string का एक हिस्सा लेती है। Syntax है s[start:stop:step]। तीनों हिस्से वैकल्पिक हैं, इसलिए बहुत थोड़े code से बहुत काम होता है।
切片取出字符串的一部分,语法是 s[start:stop:step]。三个部分都是可选的,用很少的代码就能做很多事。
stop = where to end (NOT included) — default: the end
step = how far to jump each time — default 1
stop = कहाँ ख़त्म (शामिल नहीं) — default: अंत
step = हर बार कितना कूदना — default 1
stop = 在哪里结束(不包含)—— 默认:末尾
step = 每次跳多远 —— 默认 1
s = "Python Programming"
print(repr(s[0:6]), repr(s[7:18]))
print(repr(s[:6]), repr(s[7:]), repr(s[:]))
print(repr(s[-11:]), repr(s[:-12]))
print(repr(s[::2]), repr(s[0:6:2]))
print(repr(s[::-1]))
print(repr(s[100:200])) # slicing never raises IndexError
We print with repr() so you can see the quotes. That makes the last line clear: s[100:200] is the empty string '', not an error.
हम repr() से छापते हैं ताकि quotes दिखें। इससे आख़िरी line साफ़ होती है: s[100:200] empty string '' है, error नहीं।
我们用 repr() 打印,这样能看到引号。最后一行因此一目了然:s[100:200] 是空字符串 '',而不是错误。
Slicing Cheat SheetSlicing Cheat Sheet切片速查表
| PatternPattern写法 | Meaningमतलब含义 | Example on "PYTHON""PYTHON" पर उदाहरण在 "PYTHON" 上的示例 |
|---|---|---|
| s[a:b] | Characters from index a to b-1Index a से b-1 तक के characters从索引 a 到 b-1 的字符 | s[1:4] → "YTH" |
| s[:n] | First n charactersपहले n characters前 n 个字符 | s[:3] → "PYT" |
| s[n:] | From index n to the endIndex n से अंत तक从索引 n 到末尾 | s[3:] → "HON" |
| s[-n:] | Last n charactersआख़िरी n characters最后 n 个字符 | s[-3:] → "HON" |
| s[:-n] | All except the last nआख़िरी n छोड़कर सब除最后 n 个以外的全部 | s[:-3] → "PYT" |
| s[::-1] | The whole string reversedपूरी string उल्टी整个字符串反转 | s[::-1] → "NOHTYP" |
| s[::2] | Every 2nd characterहर दूसरा character每隔一个字符 | s[::2] → "PTO" |
| s[:] | A copy of the whole stringपूरी string की copy整个字符串的副本 | s[:] → "PYTHON" |
Try s[5:1]: start is after stop and the step is +1, so nothing is picked and you get ''. Try s[10:3:-2]: a negative step walks right-to-left, so now start must be the larger index. Out-of-range numbers are quietly clipped to the ends. Only a step of 0 is an error.
s[5:1] आज़माएँ: start, stop के बाद है और step +1 है, इसलिए कुछ नहीं चुना जाता और '' मिलता है। s[10:3:-2] आज़माएँ: negative step दाएँ से बाएँ चलता है, इसलिए अब start बड़ा index होना चाहिए। सीमा से बाहर के अंक चुपचाप सिरों पर काट दिए जाते हैं। सिर्फ़ step 0 error है।
试试 s[5:1]:start 在 stop 之后且 step 为 +1,所以什么也取不到,得到 ''。试试 s[10:3:-2]:负步长从右往左走,所以 start 必须是较大的索引。越界的数字会被悄悄截到两端。只有 step 为 0 才会报错。
String Methods — The Essential Toolkit 🧰String Methods — ज़रूरी औज़ार 🧰字符串方法 —— 必备工具箱 🧰
Python strings come with 47 public methods (count them with [m for m in dir(str) if not m.startswith("_")]). You do not need to memorise them. The groups below cover almost all real work. Remember: a method never changes the original string. It returns a new value.
Python strings में 47 public methods हैं ([m for m in dir(str) if not m.startswith("_")] से गिनें)। इन्हें रटने की ज़रूरत नहीं। नीचे के समूह लगभग सारा असली काम संभाल लेते हैं। याद रखें: method असली string को कभी नहीं बदलता। वह एक नया मान लौटाता है।
Python 字符串有 47 个公开方法(用 [m for m in dir(str) if not m.startswith("_")] 数一数)。不必全部记住,下面几组几乎覆盖了所有实际工作。记住:方法从不修改原字符串,而是返回一个新值。
Case MethodsCase Methods大小写方法
text = "hello WORLD from Python"
print(text.upper())
print(text.lower())
print(text.title())
print(text.capitalize())
print(text.swapcase())
print(text) # unchanged!
text.upper() # result thrown away…
print(text) # …so text is still the same
text = text.upper() # keep the result by reassigning
print(text)
text.upper() on its own line does nothing useful: the new string is made and then thrown away. Keep it with text = text.upper(), as the last two lines show.
अकेली line में text.upper() कुछ काम का नहीं करता: नई string बनती है और फेंक दी जाती है। उसे रखने के लिए text = text.upper() लिखें, जैसा आख़िरी दो lines दिखाती हैं।
单独一行写 text.upper() 没有任何作用:新字符串生成后就被丢弃了。要保留结果,写 text = text.upper(),如最后两行所示。
Whitespace & Cleaning MethodsWhitespace और सफ़ाई Methods空白与清理方法
messy = " Hello, World! \n"
print(repr(messy.strip()))
print(repr(messy.lstrip()))
print(repr(messy.rstrip()))
url = "https://example.com/"
print(url.strip("/"))
print("xxhixyx".strip("xy")) # the argument is a SET of characters, not a word
print("report.txt".removesuffix(".txt"), "www.site.in".removeprefix("www.")) # 3.9+: remove an exact word
The argument of strip() is a set of characters. "xxhixyx".strip("xy") removes every x and y from both ends, in any order, giving hi. To remove an exact word from one end, use removeprefix() or removesuffix() (Python 3.9+).
strip() का argument characters का समूह है। "xxhixyx".strip("xy") दोनों सिरों से हर x और y किसी भी क्रम में हटाता है, और hi देता है। एक सिरे से पूरा शब्द हटाना हो तो removeprefix() या removesuffix() लगाएँ (Python 3.9+)।
strip() 的参数是一个字符集合。"xxhixyx".strip("xy") 会从两端按任意顺序删除所有 x 和 y,得到 hi。要从一端删除一个确切的单词,用 removeprefix() 或 removesuffix()(Python 3.9+)。
Search & Replace Methodsखोज और बदलाव Methods查找与替换方法
sentence = "Python is great, Python is easy"
print(sentence.find("Python"), sentence.find("Java"), sentence.rfind("Python"))
print(sentence.index("is"))
try:
sentence.index("Java")
except ValueError as err:
print("ValueError:", err)
print(sentence.count("Python"), sentence.count(" "))
print(sentence.replace("Python", "Ruby"))
print(sentence.replace("Python", "Ruby", 1))
find() returns -1 when it finds nothing; index() raises ValueError. Use index() when a missing value means a real bug.
कुछ न मिले तो find() -1 लौटाता है; index() ValueError देता है। जब ग़ायब मान असली bug हो तब index() लगाएँ।
找不到时 find() 返回 -1,而 index() 抛出 ValueError。如果找不到意味着真正的 bug,就用 index()。
split() and join() — The Power Couplesplit() और join() — दमदार जोड़ीsplit() 与 join() —— 黄金搭档
csv = "apple,banana,cherry,date"
print(csv.split(","))
print(" hello world from python ".split()) # no argument: any run of whitespace
print(csv.split(",", 2))
print("line 1\nline 2\nline 3".splitlines())
print("a,,b".split(","), "a b".split(" ")) # an explicit separator keeps empty pieces
With no argument, split() treats any run of spaces, tabs or newlines as one gap and drops empty pieces. With an explicit separator, every separator counts, so "a,,b".split(",") keeps an empty '' in the middle.
बिना argument के split() spaces, tabs या newlines की किसी भी लड़ी को एक gap मानता है और ख़ाली टुकड़े हटा देता है। साफ़ separator देने पर हर separator गिना जाता है, इसलिए "a,,b".split(",") बीच में एक ख़ाली '' रखता है।
不带参数时,split() 把任意连续的空格、制表符或换行当作一个间隔,并丢弃空片段。给出明确的分隔符时,每个分隔符都算数,所以 "a,,b".split(",") 中间会保留一个空的 ''。
words = ["Python", "is", "awesome"]
print(" ".join(words))
print("-".join(words))
print(", ".join(words))
print("".join(words))
messy = " hello world from python "
print(repr(" ".join(messy.split())))
try:
print(", ".join(["a", 1]))
except TypeError as err:
print("TypeError:", err)
print(", ".join(str(x) for x in ["a", 1]))
join() is called on the separator, and every item must already be a string. Convert numbers first, as the last line does.
join() separator पर call होता है, और हर item पहले से string होना चाहिए। संख्याओं को पहले बदलें, जैसा आख़िरी line करती है।
join() 是在分隔符上调用的,而且每一项都必须已经是字符串。先把数字转换成字符串,就像最后一行那样。
rsplit() — Splitting from the Rightrsplit() — दाएँ से काटनाrsplit() —— 从右边分割
rsplit() is the mirror image of split(). It starts cutting from the right. Without maxsplit both give the same list. The difference shows only when you limit the number of cuts.
rsplit() split() का आईना है। यह दाएँ से काटना शुरू करता है। maxsplit के बिना दोनों एक ही list देते हैं। फ़र्क़ तभी दिखता है जब आप कटों की संख्या सीमित करते हैं।
rsplit() 是 split() 的镜像,从右边开始切。不给 maxsplit 时两者结果相同,只有限制切分次数时才会看出差别。
| Behaviourव्यवहार行为 | Resultनतीजा结果 |
|---|---|
| Cuts fromकहाँ से काटता从哪边切 | Left → rightबाएँ → दाएँ左 → 右 |
| Leftover textबचा हुआ text剩余文本 | Stays on the rightदाईं ओर रहता留在右边 |
| Use whenकब लगाएँ适用于 | The start mattersशुरुआत अहम हो开头重要时 |
| Behaviourव्यवहार行为 | Resultनतीजा结果 |
|---|---|
| Cuts fromकहाँ से काटता从哪边切 | Right → leftदाएँ → बाएँ右 → 左 |
| Leftover textबचा हुआ text剩余文本 | Stays on the leftबाईं ओर रहता留在左边 |
| Use whenकब लगाएँ适用于 | The end mattersअंत अहम हो末尾重要时 |
csv = "apple,banana,cherry,date"
print(csv.split(","))
print(csv.rsplit(","))
print(csv.split(",", 1))
print(csv.rsplit(",", 1))
print(csv.split(",", 2))
print(csv.rsplit(",", 2))
filename = "my.backup.v2.tar.gz"
print(filename.split(".", 1))
name, ext = filename.rsplit(".", 1)
print(f"Name: {name}, Extension: {ext}")
full_name = "Mary Jane Watson Parker"
first_names, surname = full_name.rsplit(" ", 1)
print(f"First names: {first_names}")
print(f"Surname: {surname}")
path = "/home/asha/projects/python/hello.py"
folder, file = path.rsplit("/", 1)
print(f"Folder: {folder}")
print(f"File: {file}")
url = "https://blog.example.com/2026/python/strings-tutorial"
base, slug = url.rsplit("/", 1)
print(f"Slug: {slug}")
Use rsplit(sep, 1) whenever the last separator matters: file extensions, surnames, URL slugs, module paths ("a.b.c.func".rsplit(".", 1) → ['a.b.c', 'func']). If you catch yourself writing s.split(x)[-1], rsplit(x, 1) usually says what you mean more clearly, and it stops after one cut.
जब आख़िरी separator अहम हो तब rsplit(sep, 1) लगाएँ: file extensions, उपनाम, URL slugs, module paths ("a.b.c.func".rsplit(".", 1) → ['a.b.c', 'func'])। अगर आप s.split(x)[-1] लिख रहे हैं, तो rsplit(x, 1) आपकी बात ज़्यादा साफ़ कहता है, और एक कट के बाद रुक जाता है।
当最后一个分隔符重要时,用 rsplit(sep, 1):文件扩展名、姓氏、URL slug、模块路径("a.b.c.func".rsplit(".", 1) → ['a.b.c', 'func'])。如果你发现自己在写 s.split(x)[-1],rsplit(x, 1) 通常能更清楚地表达意图,而且切一次就停。
Checking Methods and Paddingजाँच Methods और Padding检查方法与填充
filename = "report_2026.pdf"
print(filename.startswith("report"), filename.endswith(".pdf"), filename.endswith((".pdf", ".doc")))
print("12345".isdigit(), "12.34".isdigit(), "hello".isalpha(), "hello123".isalnum())
print(" ".isspace(), "Hello".isupper(), "HELLO".isupper(), "hello".islower())
print("".isdigit(), "४२".isdigit(), "नमस्ते".isalpha()) # empty → False; Devanagari digits count;
# नमस्ते has vowel signs (्, े) that Unicode does not call letters, so isalpha() is False
name = "Asha"
print(name.ljust(15, "."))
print(name.rjust(15, "."))
print(name.center(15, "-"))
print("42".zfill(5), "-42".zfill(5))
"४२".isdigit() is True: Devanagari digits count as digits. But "नमस्ते".isalpha() is False, because vowel signs such as ् and े are "combining marks", not letters, in Unicode. An empty string gives False for every is…() check. To test "can int() read this?", the safest way is to try int(s) and catch ValueError.
"४२".isdigit() True है: देवनागरी अंक भी digits गिने जाते हैं। पर "नमस्ते".isalpha() False है, क्योंकि Unicode में ् और े जैसी मात्राएँ "combining marks" हैं, अक्षर नहीं। Empty string हर is…() जाँच में False देती है। "क्या int() इसे पढ़ सकता है?" जाँचने का सबसे सुरक्षित तरीक़ा है int(s) आज़माना और ValueError पकड़ना।
"४२".isdigit() 为 True:天城文数字也算数字。但 "नमस्ते".isalpha() 为 False,因为在 Unicode 中,像 ् 和 े 这样的元音符号是“组合标记”,不是字母。空字符串在所有 is…() 检查中都返回 False。要判断“int() 能否读取它”,最稳妥的办法是尝试 int(s) 并捕获 ValueError。
Methods ReferenceMethods सूची方法速查
| Groupसमूह类别 | MethodMethod方法 | What it doesक्या करता है作用 |
|---|---|---|
| CaseCase大小写 | .upper() / .lower() | ALL CAPS / all smallसब बड़े / सब छोटे अक्षर全大写 / 全小写 |
| .title() | Capital At The Start Of Each Wordहर शब्द का पहला अक्षर बड़ा每个单词首字母大写 | |
| .capitalize() | Only the first letter capitalसिर्फ़ पहला अक्षर बड़ा仅首字母大写 | |
| .swapcase() | Flip every caseहर case उलटें大小写互换 | |
| Cleaningसफ़ाई清理 | .strip() / .lstrip() / .rstrip() | Remove characters (whitespace by default) from both / left / right endsदोनों / बाएँ / दाएँ सिरों से characters (default: whitespace) हटाएँ从两端 / 左端 / 右端删除字符(默认空白) |
| .removeprefix() / .removesuffix() | Remove an exact word from one endएक सिरे से पूरा शब्द हटाएँ从一端删除确切的单词 | |
| Searchखोज查找 | .find() / .rfind() | First / last index, or -1पहला / आख़िरी index, या -1第一个 / 最后一个索引,或 -1 |
| .index() | Like find(), but raises ValueErrorfind() जैसा, पर ValueError देता है同 find(),但会抛出 ValueError | |
| .count() | How many times (no overlaps)कितनी बार (बिना overlap)出现次数(不重叠) | |
| .startswith() / .endswith() | Does it start / end with…? (accepts a tuple)क्या इससे शुरू / ख़त्म होता है? (tuple भी चलता)是否以……开头 / 结尾?(可传元组) | |
| Replaceबदलाव替换 | .replace(old, new, count) | Replace all, or the first countसब, या पहले count बदलें替换全部,或前 count 个 |
| Split / JoinSplit / Join分割 / 连接 | .split(sep, n) / .rsplit(sep, n) | String → list, cutting from the left / rightString → list, बाएँ / दाएँ से काटकर字符串 → 列表,从左 / 右切 |
| .splitlines() | Split at line breaksLine breaks पर काटें按换行分割 | |
| sep.join(items) | List of strings → one stringStrings की list → एक string字符串列表 → 一个字符串 | |
| Checksजाँच检查 | .isdigit() / .isalpha() / .isalnum() | All digits / letters / letters-or-digits?सब digits / अक्षर / अक्षर-या-digits?全是数字 / 字母 / 字母或数字? |
| .isspace() / .isupper() / .islower() | All whitespace / upper / lower case?सब whitespace / बड़े / छोटे?全是空白 / 大写 / 小写? | |
| PaddingPadding填充 | .ljust(n) / .rjust(n) / .center(n) | Pad to width n (text on left / right / centre)Width n तक भरें (text बाएँ / दाएँ / बीच में)填充到宽度 n(文本靠左 / 靠右 / 居中) |
| .zfill(n) | Pad with zeros, keeping a sign in frontZeros से भरें, चिह्न आगे रखते हुए用 0 填充,符号保持在最前 |
Concatenation, Repetition & Membership ➕जोड़ना, दोहराना और सदस्यता ➕拼接、重复与成员检测 ➕
+ joins two strings, * repeats one, and in / not in check whether one string appears inside another. Note that + only joins str with str.
+ दो strings जोड़ता है, * एक को दोहराता है, और in / not in जाँचते हैं कि एक string दूसरी के अंदर है या नहीं। ध्यान दें कि + सिर्फ़ str के साथ str जोड़ता है।
+ 拼接两个字符串,* 重复一个字符串,in / not in 检查一个字符串是否出现在另一个之中。注意 + 只能拼接 str 与 str。
first, last = "Hello", "World"
print(first + ", " + last + "!")
age = 25
try:
msg = "I am " + age
except TypeError as err:
print("TypeError:", err)
print("I am " + str(age))
print("-" * 40)
print("HA" * 3, "> " * 5)
sentence = "The quick brown fox jumps over the lazy dog"
print("fox" in sentence, "cat" not in sentence, "FOX" in sentence)
print("FOX".lower() in sentence.lower())
"FOX" in sentence is False because only "fox" appears. For a case-blind check, lower both sides first, as in the last line. For text in many languages, casefold() is even more thorough than lower().
"FOX" in sentence False है क्योंकि सिर्फ़ "fox" मौजूद है। Case की परवाह किए बिना जाँच के लिए पहले दोनों तरफ़ lower करें, जैसा आख़िरी line में है। कई भाषाओं वाले text के लिए casefold() lower() से भी ज़्यादा पूरा है।
"FOX" in sentence 为 False,因为只出现了 "fox"。要忽略大小写,先把两边都转成小写,如最后一行。对多语言文本,casefold() 比 lower() 更彻底。
f-Strings — Modern String Formatting 🪄f-Strings — आधुनिक String Formatting 🪄f-字符串 —— 现代字符串格式化 🪄
f-strings (formatted string literals) are Python's mail-merge. Put an
f before the quotes and write any Python expression inside {}. Python fills in the values when the line runs. They arrived in Python 3.6 and are now the usual way to build text.f-strings (formatted string literals) Python का mail-merge हैं। Quotes से पहले
f लगाएँ और {} के अंदर कोई भी Python expression लिखें। Line चलते समय Python मान भर देता है। ये Python 3.6 में आए और अब text बनाने का आम तरीक़ा हैं।f-字符串(格式化字符串字面量)就是 Python 的邮件合并。在引号前加
f,在 {} 里写任意 Python 表达式,运行到这一行时 Python 会填入值。它们在 Python 3.6 引入,如今是构建文本的常用方式。Basic f-Stringsबुनियादी f-Strings基本 f-字符串
name, age = "Asha", 30
print(f"Hello, {name}. You are {age} years old.")
print(f"Next year: {age + 1}")
print(f"Loud: {name.upper()}")
print(f"Initial: {name[0]}")
print(f"Full: {name} ({age})")
report = f"""
── User Report ────────────────
Name: {name}
Age: {age}
Adult: {age >= 18}
"""
print(report)
Format Specifiers — The Real PowerFormat Specifiers — असली ताक़त格式说明符 —— 真正的威力
After a colon inside the braces you can say how to show the value: width, alignment, decimal places, number base and more.
Braces के अंदर colon के बाद आप बता सकते हैं कि मान कैसे दिखे: चौड़ाई, alignment, दशमलव स्थान, संख्या का आधार और भी बहुत कुछ।
在花括号内的冒号之后,你可以指定值如何显示:宽度、对齐、小数位、进制等等。
| SpecSpec说明符 | Meaningमतलब含义 | Exampleउदाहरण示例 | Resultनतीजा结果 |
|---|---|---|---|
| .2f | 2 decimal places2 दशमलव स्थान保留 2 位小数 | f"{3.14159:.2f}" | 3.14 |
| .0f | No decimals (rounded)कोई दशमलव नहीं (गोल)不保留小数(四舍五入) | f"{3.99:.0f}" | 4 |
| , | Thousands separatorहज़ार का विभाजक千位分隔符 | f"{1000000:,}" | 1,000,000 |
| ,.2f | Thousands + 2 decimalsहज़ार विभाजक + 2 दशमलव千位分隔 + 2 位小数 | f"{1234.5:,.2f}" | 1,234.50 |
| .1% | Percentageप्रतिशत百分比 | f"{0.856:.1%}" | 85.6% |
| .2e | Scientific notationScientific notation科学计数法 | f"{1234567:.2e}" | 1.23e+06 |
| b / o | Binary / octalBinary / octal二进制 / 八进制 | f"{10:b}" | 1010 |
| x / X | Hex (lower / upper)Hex (छोटे / बड़े)十六进制(小写 / 大写) | f"{255:X}" | FF |
| 05d | Zero-pad to width 5Width 5 तक zeros用 0 补到宽度 5 | f"{42:05d}" | 00042 |
| <10 | Left-align, width 10बाएँ, width 10左对齐,宽度 10 | f"{'hi':<10}|" | "hi |" |
| >10 | Right-align, width 10दाएँ, width 10右对齐,宽度 10 | f"{'hi':>10}|" | " hi|" |
| ^10 | Centre, width 10बीच में, width 10居中,宽度 10 | f"{'hi':^10}|" | " hi |" |
price = 12345.678
print(f"Price: ₹{price:,.2f}")
pass_rate = 0.847
print(f"Pass rate: {pass_rate:.1%}")
print(f"{'NAME':<10}{'AGE':>5}{'SCORE':>10}")
print(f"{'-' * 25}")
print(f"{'Asha':<10}{30:>5}{95.5:>10.1f}")
print(f"{'Ravi':<10}{25:>5}{88.2:>10.1f}")
print(f"{'Meena':<10}{35:>5}{92.7:>10.1f}")
x = 42
print(f"{x=}")
from datetime import datetime
when = datetime(2026, 10, 29, 14, 23, 45) # a fixed time so the output is repeatable
print(f"Date: {when:%Y-%m-%d}")
print(f"Time: {when:%H:%M:%S}")
print(f"{3.99:.0f} {1234567:.2e} {10:b} {10:o} {255:X} {42:05d}")
Since Python 3.8, f"{x=}" prints both the expression and its value — x=42 above. It is the fastest way to inspect a variable while debugging.
Python 3.8 से f"{x=}" expression और उसका मान दोनों छापता है — ऊपर x=42। Debugging के दौरान variable देखने का यह सबसे तेज़ तरीक़ा है।
从 Python 3.8 起,f"{x=}" 会同时打印表达式和它的值 —— 上面的 x=42。这是调试时查看变量最快的办法。
Older Formatting Styles — For Reading Old Codeपुराने Formatting तरीक़े — पुराना Code पढ़ने के लिए旧式格式化 —— 用于阅读旧代码
| Styleतरीक़ा写法 | Exampleउदाहरण示例 |
|---|---|
| % formatting% formatting% 格式化 | "Hi, %s" % name |
| .format() | "Hi, {}".format(name) |
| Concatenationजोड़ना拼接 | "Hi, " + name |
| Styleतरीक़ा写法 | Exampleउदाहरण示例 |
|---|---|
| f-string | f"Hi, {name}" |
| Speedगति速度 | About 1.0× faster than .format() in the test belowनीचे के test में .format() से लगभग 1.0× तेज़在下面的测试中比 .format() 快约 1.0 倍 |
| Readableपढ़ने में आसान可读性 | Values sit right where they appearमान वहीं दिखते हैं जहाँ छपेंगे值就写在它出现的位置 |
import timeit
name, age = "Asha", 30
for label, stmt in [("f-string ", 'f"Hi, {name}, {age}"'),
(".format()", '"Hi, {}, {}".format(name, age)'),
("% style ", '"Hi, %s, %s" % (name, age)')]:
best = min(timeit.repeat(stmt, globals=globals(), number=200_000, repeat=7))
print(f"{label}: {best * 5:.3f} s per million") # best of 7 runs
On this machine (Python 3.13.16), f-strings took 0.143 s per million, .format() took 0.140 s, and % took 0.086 s. So f-strings clearly beat .format(), while old % style is about as fast. Pick f-strings for readability first; the speed is a bonus. (The logging module still uses %-style placeholders on purpose.)
इस machine पर (Python 3.13.16) f-strings ने प्रति दस लाख 0.143 s लिए, .format() ने 0.140 s, और % ने 0.086 s। यानी f-strings .format() से साफ़ आगे हैं, जबकि पुराना % तरीक़ा लगभग उतना ही तेज़ है। f-strings पहले पढ़ने में आसानी के लिए चुनें; गति बोनस है। (logging module जान-बूझकर अब भी % वाले placeholders लेता है।)
在这台机器上(Python 3.13.16),f-字符串每百万次耗时 0.143 秒,.format() 耗时 0.140 秒,% 耗时 0.086 秒。所以 f-字符串明显快于 .format(),而老式 % 速度差不多。选择 f-字符串首先是为了可读性,速度只是额外收获。(logging 模块至今仍有意使用 % 风格的占位符。)
Escape Characters, Raw Strings & Unicode 🔣Escape Characters, Raw Strings और Unicode 🔣转义字符、原始字符串与 Unicode 🔣
Sometimes a string needs a character that would confuse Python: a quote inside quotes, a new line, a tab, or a real backslash. That is what escape sequences are for. They all start with a backslash \.
कभी-कभी string में ऐसा character चाहिए जो Python को उलझा दे: quotes के अंदर quote, नई line, tab, या असली backslash। इसी के लिए escape sequences हैं। ये सब backslash \ से शुरू होते हैं।
有时字符串需要一个会让 Python 困惑的字符:引号里的引号、换行、制表符或真正的反斜杠。这就是转义序列的用途,它们都以反斜杠 \ 开头。
| EscapeEscape转义 | Meaningमतलब含义 |
|---|---|
| \n | New lineनई line换行 |
| \t | TabTab制表符 |
| \\ | A real backslashअसली backslash一个真正的反斜杠 |
| \' | Single quoteSingle quote单引号 |
| \" | Double quoteDouble quote双引号 |
| \r | Carriage return (rare)Carriage return (कम)回车(少见) |
| \0 | Null character (low-level data)Null character (low-level data)空字符(底层数据) |
| \u00e9 | Unicode character by 4-digit hex code4-अंकी hex code से Unicode character用 4 位十六进制码表示的 Unicode 字符 |
| \N{...} | Unicode character by nameनाम से Unicode character按名称表示的 Unicode 字符 |
print("Line 1\nLine 2")
print("Name:\tAsha")
print("She said \"hi\"")
print('It\'s fine')
print("C:\\Users\\Asha")
print(r"C:\Users\new_folder")
print("caf\u00e9", "\N{GREEK SMALL LETTER PI}", "\U0001F600")
print(len("C:\new"), repr("C:\new")) # \n is ONE character (a newline): the path is broken
Look at the last line: "C:\new" has length 5, not 6, because \n became one newline character. The path broke silently. A \U is even worse — Python cannot even read the file:
आख़िरी line देखिए: "C:\new" की length 5 है, 6 नहीं, क्योंकि \n एक newline character बन गया। Path चुपचाप टूट गया। \U तो और बुरा है — Python file पढ़ ही नहीं पाता:
看最后一行:"C:\new" 的长度是 5 而不是 6,因为 \n 变成了一个换行符。路径被悄无声息地破坏了。\U 更糟 —— Python 连文件都读不了:
print("C:\Users\new_folder")
For Windows paths, use a raw string: r"C:\Users\Asha". Without the r, \n and \t silently become a newline and a tab, and \U or \x stop the program with a SyntaxError. Forward slashes also work on Windows: "C:/Users/Asha". Even better, use pathlib.Path.
Windows paths के लिए raw string लगाएँ: r"C:\Users\Asha"। r के बिना \n और \t चुपचाप newline और tab बन जाते हैं, और \U या \x SyntaxError से program रोक देते हैं। Windows पर forward slashes भी चलते हैं: "C:/Users/Asha"। और भी अच्छा, pathlib.Path लगाएँ।
Windows 路径请用原始字符串:r"C:\Users\Asha"。不加 r,\n 和 \t 会悄悄变成换行和制表符,而 \U 或 \x 会让程序直接报 SyntaxError。正斜杠在 Windows 上也能用:"C:/Users/Asha"。更好的做法是用 pathlib.Path。
Unicode: Every Language Is WelcomeUnicode: हर भाषा का स्वागतUnicode:欢迎所有语言
A Python 3 string is a sequence of Unicode code points, so Hindi, Chinese and emoji work out of the box. len() counts code points, ord() gives a character's number, and chr() turns a number back into a character.
Python 3 की string Unicode code points का क्रम है, इसलिए हिन्दी, चीनी और emoji सीधे काम करते हैं। len() code points गिनता है, ord() किसी character का अंक देता है, और chr() अंक को वापस character बनाता है।
Python 3 的字符串是 Unicode 码位(code point)的序列,所以印地语、中文和 emoji 都能直接使用。len() 统计码位数,ord() 给出字符的编号,chr() 把编号变回字符。
for word in ["Python", "नमस्ते", "你好", "😀"]:
print(repr(word), "len =", len(word), "| first code point =", ord(word[0]))
print(chr(65), chr(2350), chr(20320))
print("apple" < "banana", "Zebra" < "apple", ord("Z"), ord("a"))
print(sorted(["banana", "apple", "Cherry"]))
print(sorted(["banana", "apple", "Cherry"], key=str.lower))
1. len("नमस्ते") is 6, although you see 3 syllables: vowel signs and the virama ् are separate code points. len("你好") is 2 — one per character, not bytes.
2. Strings compare by code point, and every capital letter (Z = 90) comes before every small letter (a = 97). So "Zebra" < "apple" is True, and sorted() puts "Cherry" first. Use key=str.lower for a natural A–Z order.
1. len("नमस्ते") 6 है, भले ही आपको 3 अक्षर दिखें: मात्राएँ और हलंत ् अलग code points हैं। len("你好") 2 है — हर character का एक, bytes नहीं।
2. Strings की तुलना code point से होती है, और हर बड़ा अक्षर (Z = 90) हर छोटे अक्षर (a = 97) से पहले आता है। इसलिए "Zebra" < "apple" True है, और sorted() "Cherry" को पहले रखता है। स्वाभाविक A–Z क्रम के लिए key=str.lower लगाएँ।
1. len("नमस्ते") 是 6,尽管你只看到 3 个音节:元音符号和半音符 ् 都是独立的码位。len("你好") 是 2 —— 每个汉字一个,而不是字节数。
2. 字符串按码位比较,所有大写字母(Z = 90)都排在所有小写字母(a = 97)之前。所以 "Zebra" < "apple" 为 True,sorted() 会把 "Cherry" 排在最前。想要自然的 A–Z 顺序,用 key=str.lower。
Iterating Over Strings 🔁Strings पर Loop 🔁遍历字符串 🔁
A string is a sequence, so a for loop walks through it one character at a time. Use enumerate() when you also need the index.
String एक sequence है, इसलिए for loop उसमें एक-एक character चलता है। Index भी चाहिए तो enumerate() लगाएँ।
字符串是序列,所以 for 循环会逐个字符遍历它。还需要索引时,用 enumerate()。
word = "Python"
for letter in word:
print(letter, end=" ")
print()
for i, letter in enumerate(word):
print(f"Index {i}: {letter}")
sentence = "The quick brown fox jumps"
vowels = "aeiouAEIOU"
count = 0
for char in sentence:
if char in vowels:
count += 1
print(f"Vowel count: {count}")
print(f"Vowel count: {sum(1 for c in sentence if c in vowels)}")
The last line does the same count in one line with sum() and a generator. Both ways print 6.
आख़िरी line वही गिनती sum() और generator से एक line में करती है। दोनों तरीक़े 6 छापते हैं।
最后一行用 sum() 加生成器在一行里完成同样的计数,两种方式都输出 6。
Complete Practice Program — String Toolkit 🛠️पूरा अभ्यास Program — String Toolkit 🛠️完整练习程序 —— 字符串工具箱 🛠️
This program uses every idea from the lesson — creation, indexing, slicing, methods, iteration and f-strings — in one working script. The output below is a real run.
यह program lesson का हर विचार — बनाना, indexing, slicing, methods, iteration और f-strings — एक चलती script में इस्तेमाल करता है। नीचे का output असली run है।
这个程序在一个可运行的脚本里用到了本课的所有概念 —— 创建、索引、切片、方法、遍历和 f-字符串。下面的输出是真实运行结果。
# string_toolkit.py — All string concepts in one program
def analyse_text(text):
"""Analyse a string and return a report dictionary."""
return {
"length": len(text),
"words": len(text.split()),
"upper": text.upper(),
"lower": text.lower(),
"reversed": text[::-1],
"first_word": text.split()[0] if text.strip() else "",
"last_word": text.split()[-1] if text.strip() else "",
"vowels": sum(1 for c in text.lower() if c in "aeiou"),
"digits": sum(1 for c in text if c.isdigit()),
"spaces": text.count(" "),
}
def format_report(text, stats):
"""Build a nicely formatted report using f-strings."""
line = "═" * 50
return f"""
{line}
STRING ANALYSIS REPORT
{line}
Input: "{text[:40]}{'...' if len(text) > 40 else ''}"
Length: {stats['length']:>5} characters
Words: {stats['words']:>5}
Vowels: {stats['vowels']:>5}
Digits: {stats['digits']:>5}
Spaces: {stats['spaces']:>5}
First word: {stats['first_word']}
Last word: {stats['last_word']}
Uppercase: {stats['upper'][:40]}
Reversed: {stats['reversed'][:40]}
{line}
"""
def main():
# Sample text — try changing this!
sample = "Python is a POWERFUL programming language, released in 1991."
# Analyse and display
stats = analyse_text(sample)
print(format_report(sample, stats))
# Bonus: check some properties using string methods
print(f" Contains 'Python'? {'Python' in sample}")
print(f" Starts with 'Py'? {sample.startswith('Py')}")
print(f" Ends with '.'? {sample.endswith('.')}")
# Clean and rebuild sentence — the split+join pattern
normalised = " ".join(sample.lower().split())
print(f"\n Normalised: {normalised}")
if __name__ == "__main__":
main()
Words 9 comes from split(). Vowels 18 uses lower() plus a loop with in. Digits 4 is the "1991". The input is cut with text[:40] and gets "..." because the text has 60 characters. [::-1] makes the reversed line, :>5 lines up the numbers, and " ".join(...split()) cleans the spacing.
Words 9 split() से आता है। Vowels 18 lower() और in वाले loop से। Digits 4 यानी "1991"। Input text[:40] से कटता है और "..." लगता है क्योंकि text में 60 characters हैं। [::-1] उल्टी line बनाता है, :>5 अंकों को सीध में लाता है, और " ".join(...split()) spacing साफ़ करता है।
Words 9 来自 split()。Vowels 18 用了 lower() 加带 in 的循环。Digits 4 就是 "1991"。输入用 text[:40] 截断并加上 "...",因为文本有 60 个字符。[::-1] 生成反转的一行,:>5 让数字对齐," ".join(...split()) 整理空格。
Golden Rules 🏆सुनहरे नियम 🏆黄金法则 🏆
Six questions on strings. Pick an answer to see why.
Strings पर छह सवाल। जवाब चुनें और कारण देखें।
关于字符串的六道题。选择答案查看解释。
A string is an immutable sequence of characters. Read one character with s[i] (negative indexes count from the end), take a piece with s[start:stop:step] (stop is not included), and remember that every method returns a new value. Use split()/rsplit() and join() to move between text and lists, f-strings to format, raw strings for backslashes, and == to compare.
String characters का immutable sequence है। एक character s[i] से पढ़ें (negative indexes अंत से गिनते हैं), टुकड़ा s[start:stop:step] से लें (stop शामिल नहीं), और याद रखें कि हर method नया मान लौटाता है। Text और lists के बीच आने-जाने के लिए split()/rsplit() और join(), formatting के लिए f-strings, backslashes के लिए raw strings, और तुलना के लिए == लगाएँ।
字符串是字符的不可变序列。用 s[i] 读取单个字符(负索引从末尾数),用 s[start:stop:step] 取出一段(不含 stop),并记住每个方法都返回新值。用 split()/rsplit() 和 join() 在文本与列表之间转换,用 f-字符串格式化,用原始字符串处理反斜杠,用 == 进行比较。