BASIC Python (Beginner Level) 📂 Basic Python Programming · 7 of 15 196 min read

Python Strings — Immutability, Indexing, Slicing, Methods & f-Strings Explained

Master Python strings from the ground up. This tutorial explains the four ways to create strings, the exact meaning of immutability and the four reasons Python enforces it, zero-based and negative indexing, complete slicing syntax with start/stop/step, 50+ built-in string methods with categorised examples (case, cleaning, search, split/join, checking, padding), modern f-string formatting with format specifiers, escape sequences, and a full practice program.

🌐
SectionSection第 01 节

The Story That Explains Strings 📿Strings समझाने वाली कहानी 📿一个解释字符串的故事 📿

Beads on a Stringधागे में पिरोए मोती串在线上的珠子
Imagine a jewellery maker holding a string of beads. Each bead has a letter on it: H, E, L, L, O. Together they spell "HELLO". You can look at any bead by counting from the left (bead 0 is 'H', bead 4 is 'O'). You can take a section of beads (beads 1 to 3 spell "ELL"). You can make a new string with the same beads plus more (add "!" to get "HELLO!").

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, E, L, L, O। मिलकर वे "HELLO" बनाते हैं। बाएँ से गिनकर आप कोई भी मोती देख सकते हैं (मोती 0 'H' है, मोती 4 'O')। आप मोतियों का एक हिस्सा ले सकते हैं (मोती 1 से 3 "ELL" बनाते हैं)। आप उन्हीं मोतियों और कुछ और से नई माला बना सकते हैं ("!" जोड़कर "HELLO!")।

पर एक शर्त है: यह संग्रहालय की चीज़ है। धागे पर लगे मोती को बदलने की इजाज़त नहीं। अगर 'H' को 'J' करके "JELLO" चाहिए, तो एक बिल्कुल नई माला बनानी होगी। असली "HELLO" जैसी थी वैसी रहती है।

Python strings ठीक ऐसे ही काम करती हैं। वे characters का क्रम (sequence) हैं जिन्हें आप देख, काट (slice) और जोड़ सकते हैं — पर अपनी जगह पर कभी बदल नहीं सकते। इस गुण को immutability कहते हैं, और यह Python के सबसे अहम design फ़ैसलों में से एक है।
想象一位首饰匠手里拿着一串珠子。每颗珠子上有一个字母:H、E、L、L、O,合起来拼成 "HELLO"。你可以从左数,查看任意一颗珠子(第 0 颗是 'H',第 4 颗是 'O');可以取出一段珠子(第 1 到 3 颗拼成 "ELL");也可以用同样的珠子再加几颗做一串新的(加上 "!" 得到 "HELLO!")。

但有一个限制:这是一件博物馆展品。珠子一旦串上,就不允许更换。如果想把 'H' 换成 'J' 得到 "JELLO",你必须做一串全新的。原来的 "HELLO" 保持不变。

Python 的字符串正是这样工作的。它们是字符序列,可以查看、切片、拼接 —— 但永远不能原地修改。这个特性叫做不可变性(immutability),是 Python 最重要的设计决定之一。
📿 One string, two ways to count📿 एक string, गिनने के दो तरीक़े📿 一个字符串,两种计数方式
HELLO as beads with positive and negative indexesH0-5E1-4L2-3L3-2O4-1"HELLO"[1:4] → "ELL"

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。它是真实程序中你最常用的数据类型。

💡
Two Facts to Rememberयाद रखने लायक़ दो बातें要记住的两个事实

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. 字符串是不可变的 —— 创建后内容不能改变。每次“修改”都会产生一个全新的字符串。


SectionSection第 02 节

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 程序员的第一个标志。

'
Single QuotesSingle Quotes单引号
'text'
The standard form. Handy when the text has double quotes in it: 'She said "hi"'.
सामान्य रूप। जब text में double quotes हों तब काम का: 'She said "hi"'।
标准写法。文本中含有双引号时很方便:'She said "hi"'。
"
Double QuotesDouble Quotes双引号
"text"
Exactly the same as single quotes. Handy when the text has an apostrophe: "it's fine".
Single quotes जैसा ही। जब text में apostrophe हो तब काम का: "it's fine"।
与单引号完全相同。文本中含有撇号时很方便:"it's fine"。
…
Triple QuotesTriple Quotes三引号
"""text"""
Multi-line text. Keeps newlines and spaces exactly. Also used for docstrings in functions and classes.
कई lines वाला text। नई lines और spaces जैसे के तैसे रखता है। Functions और classes में docstrings के लिए भी।
多行文本,原样保留换行和空格。也用于函数和类中的文档字符串(docstring)。
🔁
Raw StringsRaw Strings原始字符串
r"text"
Backslashes stay as they are. Great for Windows paths and regular expressions: r"C:\Users\Asha".
Backslash जैसे के तैसे रहते हैं। Windows paths और regular expressions के लिए बढ़िया: r"C:\Users\Asha"।
反斜杠保持原样。非常适合 Windows 路径和正则表达式:r"C:\Users\Asha"。
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
OUTPUT
Asha Hello, World! She said "Python is fun" | it's a wonderful day Roses are red, Violets are blue, Python is awesome, And so are you. C:\Users\Asha\new_folder \d+\.\d+ '' 0 False
⚠️
The Empty String Is a Real StringEmpty String भी असली String है空字符串也是真正的字符串

"" 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:。


SectionSection第 03 节

Immutability — What It Really Means 🔒Immutability — असल में इसका मतलब 🔒不可变性 —— 真正的含义 🔒

A Printed Bookछपी हुई किताब一本印好的书
Think of a printed hardcover book. Once it leaves the press, you cannot change the words inside. You can read any page. You can photocopy pages. You can write a new book with edits. But you cannot change "The cat sat" to "The dog sat" on page 47 — the ink is fixed.

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.
एक छपी हुई hardcover किताब सोचिए। Press से निकलने के बाद आप उसके शब्द नहीं बदल सकते। आप कोई भी पन्ना पढ़ सकते हैं, पन्नों की photocopy कर सकते हैं, बदलावों के साथ नई किताब लिख सकते हैं। पर पन्ना 47 पर "The cat sat" को "The dog sat" नहीं कर सकते — स्याही पक्की है।

Python strings छपी किताबें हैं। बनने के बाद उनके अंदर के characters कभी नहीं बदलते। जो भी काम string को "बदलता" लगता है, वह असल में नई string बनाता है और असली को छोड़ देता है।
想象一本印好的精装书。一旦印出,你就无法更改里面的文字。你可以阅读任何一页,可以复印,也可以写一本修改过的新书。但你不能把第 47 页的 "The cat sat" 改成 "The dog sat" —— 油墨已经固定了。

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
OUTPUT
TypeError: 'str' object does not support item assignment hello HELLO False Asha Verma False
🏷️ Reassignment is not mutation🏷️ नया नाम देना बदलना नहीं है🏷️ 重新赋值不等于修改
Reassignment moves the name to a new objectname'Asha''Asha Verma'unchanged, no longer usedबदली नहीं, अब इस्तेमाल में नहीं未被修改,已不再使用name = name + " Verma" → a NEW objectname = name + " Verma" → एक नया objectname = name + " Verma" → 一个新对象

The label name moves to a new object. The old 'Asha' is never edited.

Label name नए object पर चला जाता है। पुराना 'Asha' कभी बदला नहीं जाता।

标签 name 移到了新对象上,旧的 'Asha' 从未被修改。

🔎
About the Memory NumbersMemory वाले अंकों के बारे में关于内存编号

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 不可变 —— 并排对比

❌ Mutable — list, dict, setMutable — list, dict, set可变 —— list、dict、set
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 नहीं不产生新列表
✅ Immutable — str, int, float, bool, tupleImmutable — str, int, float, bool, tuple不可变 —— str、int、float、bool、tuple
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]) 不能。


SectionSection第 04 节

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 的设计者有意让字符串不可变,背后有四个有力的理由。了解它们能帮你判断什么时候用字符串、什么时候用列表。

⚡
Speed & Hashingगति और Hashing速度与哈希
hash = compute oncehash = एक बार गणना哈希只算一次
Because a string never changes, Python computes its hash once and stores it. That makes strings fast dictionary keys and set members. Lists can change, so they cannot be hashed.
String कभी नहीं बदलती, इसलिए Python उसका hash एक बार निकालकर रख लेता है। इससे strings तेज़ dictionary keys और set के सदस्य बनती हैं। Lists बदल सकती हैं, इसलिए उनका hash नहीं बनता।
因为字符串永不改变,Python 只计算一次哈希并缓存。这让字符串成为高效的字典键和集合成员。列表可以改变,所以不能被哈希。
🔒
Thread SafetyThread सुरक्षा线程安全
no race conditionsकोई race condition नहीं没有竞态条件
Many threads can read the same string at once with no risk of corruption and no locks. If nothing can change, nothing can go wrong.
कई threads एक ही string को एक साथ बिना बिगड़ने के डर और बिना locks के पढ़ सकते हैं। जब कुछ बदल ही नहीं सकता, तो कुछ गड़बड़ भी नहीं हो सकती।
多个线程可以同时读取同一个字符串,没有损坏风险,也不需要加锁。什么都不会变,就什么都不会出错。
🧩
Saving Memory (Interning)Memory बचत (Interning)节省内存(驻留)
same text → may share one objectवही text → एक object साझा हो सकता है相同文本 → 可能共享一个对象
CPython reuses one object for many identical short strings, such as names in your code and literals that look like identifiers. This is only safe because no one can change the shared string.
CPython कई एक जैसी छोटी strings के लिए एक ही object दोबारा इस्तेमाल करता है, जैसे code में नाम और identifier जैसे दिखने वाले literals। यह तभी सुरक्षित है जब साझा string को कोई बदल न सके।
CPython 会为许多相同的短字符串复用同一个对象,例如代码中的名字和看起来像标识符的字面量。只有当共享的字符串无法被修改时,这样做才安全。
🎯
Predictable Codeभरोसेमंद Code可预测的代码
no hidden side effectsकोई छिपा असर नहीं没有隐藏的副作用
When you pass a string to a function, you know it cannot be changed by that function. A whole class of "who changed my data?" bugs disappears.
जब आप किसी function को string देते हैं, तो आप जानते हैं कि वह उसे बदल नहीं सकता। "मेरा data किसने बदला?" वाले bugs की पूरी श्रेणी ग़ायब हो जाती है।
把字符串传给函数时,你知道它不会被该函数修改。一整类“谁改了我的数据?”的 bug 就此消失。

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)
OUTPUT
True True False 30 True TypeError: unhashable type: 'list'
⚠️
Never Use "is" to Compare TextText की तुलना के लिए "is" कभी न लगाएँ永远不要用 "is" 比较文本

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 的实现细节,不是保证。比较字符串的值,永远用 ==。

🎯
A Trade-Off Worth Makingफ़ायदे का सौदा值得的取舍

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 允许原地修改字符串。)


SectionSection第 05 节

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。你也可以用负索引从末尾倒着数。

📏 Indexing "PYTHON""PYTHON" की Indexing"PYTHON" 的索引
CharacterCharacter字符
PYTHON
PYTHON
PYTHON
PositivePositive正索引
0 1 2 3 4 5 — counts from the left, starts at 0
0 1 2 3 4 5 — बाएँ से गिनती, 0 से शुरू
0 1 2 3 4 5 —— 从左数,从 0 开始
NegativeNegative负索引
-6 -5 -4 -3 -2 -1 — counts from the right, starts at -1
-6 -5 -4 -3 -2 -1 — दाएँ से गिनती, -1 से शुरू
-6 -5 -4 -3 -2 -1 —— 从右数,从 -1 开始
LengthLength长度
len("PYTHON") = 6 — the number of characters
len("PYTHON") = 6 — characters की गिनती
len("PYTHON") = 6 —— 字符个数
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)
OUTPUT
P Y N N O P 6 Alexander starts with 'A' and ends with 'r' IndexError: string index out of range
🔑
Negative Indexing Is a SuperpowerNegative Indexing एक ख़ास ताक़त है负索引是超能力

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] 直接就行。大胆使用负索引,它符合人的思维方式(“倒数第二个”)。

🔍 Index Explorer — s[i]Index Explorer — s[i]索引探索器 —— s[i]Type a word and an index, or click any boxकोई शब्द और index लिखें, या किसी box पर click करें输入一个单词和索引,或点击任意方块
Quick:जल्दी:快捷:
top number = positive index · bottom number = negative indexऊपर का अंक = positive index · नीचे का अंक = negative index上方数字 = 正索引 · 下方数字 = 负索引

SectionSection第 06 节

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]。三个部分都是可选的,用很少的代码就能做很多事。

Slice SyntaxSlice Syntax切片语法
s[start : stop : step]
start = where to begin (included) — default 0
stop = where to end (NOT included) — default: the end
step = how far to jump each time — default 1
start = कहाँ से शुरू (शामिल) — default 0
stop = कहाँ ख़त्म (शामिल नहीं) — default: अंत
step = हर बार कितना कूदना — default 1
start = 从哪里开始(包含)—— 默认 0
stop = 在哪里结束(不包含)—— 默认:末尾
step = 每次跳多远 —— 默认 1
Golden Ruleसुनहरा नियम黄金法则
stop is EXCLUSIVEstop शामिल नहींstop 不包含
s[2:5] gives indexes 2, 3, 4 — not 5. Every beginner trips on this once.
s[2:5] indexes 2, 3, 4 देता है — 5 नहीं। हर नौसिखिया इस पर एक बार फिसलता है।
s[2:5] 给出索引 2、3、4 —— 不含 5。每个初学者都会在这里栽一次。
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
OUTPUT
'Python' 'Programming' 'Python' 'Programming' 'Python Programming' 'Programming' 'Python' 'Pto rgamn' 'Pto' 'gnimmargorP nohtyP' ''

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"
✂️ Slice Simulator — s[start:stop:step]Slice Simulator — s[start:stop:step]切片模拟器 —— s[start:stop:step]Leave a box empty to use its defaultDefault के लिए box ख़ाली छोड़ें留空即使用默认值
s[::]
Try:आज़माएँ:试试:
🧭
How Python Handles Odd Slicesअजीब Slices को Python कैसे संभालता है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 才会报错。


SectionSection第 07 节

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("_")] 数一数)。不必全部记住,下面几组几乎覆盖了所有实际工作。记住:方法从不修改原字符串,而是返回一个新值。

🧰 String Method SimulatorString Method Simulator字符串方法模拟器Pick a method, change the text, and watch every characterMethod चुनें, text बदलें, और हर character देखें选择方法、修改文本,观察每个字符

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)
OUTPUT
HELLO WORLD FROM PYTHON hello world from python Hello World From Python Hello world from python HELLO world FROM pYTHON hello WORLD from Python hello WORLD from Python HELLO WORLD FROM PYTHON
⚠️
The #1 Beginner Mistakeनौसिखियों की सबसे आम ग़लती初学者头号错误

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
OUTPUT
'Hello, World!' 'Hello, World! \n' ' Hello, World!' https://example.com hi report site.in
🧪
strip("xy") Removes Characters, Not a Wordstrip("xy") शब्द नहीं, characters हटाता हैstrip("xy") 删除的是字符,不是单词

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))
OUTPUT
0 -1 17 7 ValueError: substring not found 2 5 Ruby is great, Ruby is easy Ruby is great, Python is easy

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
OUTPUT
['apple', 'banana', 'cherry', 'date'] ['hello', 'world', 'from', 'python'] ['apple', 'banana', 'cherry,date'] ['line 1', 'line 2', 'line 3'] ['a', '', 'b'] ['a', '', 'b']
💡
split() vs split(" ")split() बनाम split(" ")split() 与 split(" ") 的区别

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]))
OUTPUT
Python is awesome Python-is-awesome Python, is, awesome Pythonisawesome 'hello world from python' TypeError: sequence item 1: expected str instance, int found 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 时两者结果相同,只有限制切分次数时才会看出差别。

✂️ split(sep, maxsplit)
Behaviourव्यवहार行为Resultनतीजा结果
Cuts fromकहाँ से काटता从哪边切Left → rightबाएँ → दाएँ左 → 右
Leftover textबचा हुआ text剩余文本Stays on the rightदाईं ओर रहता留在右边
Use whenकब लगाएँ适用于The start mattersशुरुआत अहम हो开头重要时
✂️ rsplit(sep, maxsplit)
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}")
OUTPUT
['apple', 'banana', 'cherry', 'date'] ['apple', 'banana', 'cherry', 'date'] ['apple', 'banana,cherry,date'] ['apple,banana,cherry', 'date'] ['apple', 'banana', 'cherry,date'] ['apple,banana', 'cherry', 'date'] ['my', 'backup.v2.tar.gz'] Name: my.backup.v2.tar, Extension: gz First names: Mary Jane Watson Surname: Parker Folder: /home/asha/projects/python File: hello.py Slug: strings-tutorial
🔑
When to Reach for rsplitrsplit कब लगाएँ什么时候用 rsplit

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))
OUTPUT
True True True True False True True True False True True False True False Asha........... ...........Asha ------Asha----- 00042 -0042
🌏
The is…() Methods Understand Unicodeis…() Methods Unicode समझते हैंis…() 方法理解 Unicode

"४२".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 填充,符号保持在最前

SectionSection第 08 节

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())
OUTPUT
Hello, World! TypeError: can only concatenate str (not "int") to str I am 25 ---------------------------------------- HAHAHA > > > > > True True False True
🔑
in Is Case-Sensitivein Case-Sensitive हैin 区分大小写

"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() 更彻底。


SectionSection第 09 节

f-Strings — Modern String Formatting 🪄f-Strings — आधुनिक String Formatting 🪄f-字符串 —— 现代字符串格式化 🪄

Mail-Merge for StringsStrings के लिए Mail-Merge字符串的邮件合并
Think of a newsletter that opens with "Dear {first_name}". The template stays the same; only the blank changes for each reader. Mail-merge fills in the blanks and makes a personal message.

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.
एक newsletter सोचिए जो "Dear {first_name}" से शुरू होता है। Template वही रहता है; हर पाठक के लिए सिर्फ़ ख़ाली जगह बदलती है। Mail-merge ख़ाली जगह भरकर निजी संदेश बनाता है।

f-strings (formatted string literals) Python का mail-merge हैं। Quotes से पहले f लगाएँ और {} के अंदर कोई भी Python expression लिखें। Line चलते समय Python मान भर देता है। ये Python 3.6 में आए और अब text बनाने का आम तरीक़ा हैं।
想象一份以 "Dear {first_name}" 开头的通讯。模板不变,只有空白处因读者而异。邮件合并把空白填好,生成个性化的信息。

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)
OUTPUT
Hello, Asha. You are 30 years old. Next year: 31 Loud: ASHA Initial: A Full: Asha (30) ── User Report ──────────────── Name: Asha Age: 30 Adult: True

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नतीजा结果
.2f2 decimal places2 दशमलव स्थान保留 2 位小数f"{3.14159:.2f}"3.14
.0fNo decimals (rounded)कोई दशमलव नहीं (गोल)不保留小数(四舍五入)f"{3.99:.0f}"4
,Thousands separatorहज़ार का विभाजक千位分隔符f"{1000000:,}"1,000,000
,.2fThousands + 2 decimalsहज़ार विभाजक + 2 दशमलव千位分隔 + 2 位小数f"{1234.5:,.2f}"1,234.50
.1%Percentageप्रतिशत百分比f"{0.856:.1%}"85.6%
.2eScientific notationScientific notation科学计数法f"{1234567:.2e}"1.23e+06
b / oBinary / octalBinary / octal二进制 / 八进制f"{10:b}"1010
x / XHex (lower / upper)Hex (छोटे / बड़े)十六进制(小写 / 大写)f"{255:X}"FF
05dZero-pad to width 5Width 5 तक zeros用 0 补到宽度 5f"{42:05d}"00042
<10Left-align, width 10बाएँ, width 10左对齐,宽度 10f"{'hi':<10}|""hi        |"
>10Right-align, width 10दाएँ, width 10右对齐,宽度 10f"{'hi':>10}|""        hi|"
^10Centre, width 10बीच में, width 10居中,宽度 10f"{'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}")
OUTPUT
Price: ₹12,345.68 Pass rate: 84.7% NAME AGE SCORE ------------------------- Asha 30 95.5 Ravi 25 88.2 Meena 35 92.7 x=42 Date: 2026-10-29 Time: 14:23:45 4 1.23e+06 1010 12 FF 00042
🐞
The Debug Shortcut: {x=}Debug का शॉर्टकट: {x=}调试捷径:{x=}

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 पढ़ने के लिए旧式格式化 —— 用于阅读旧代码

🕰️ Older ways (you will still meet them)पुराने तरीक़े (अब भी दिखेंगे)旧写法(你仍会遇到)
Styleतरीक़ा写法Exampleउदाहरण示例
% formatting% formatting% 格式化"Hi, %s" % name
.format()"Hi, {}".format(name)
Concatenationजोड़ना拼接"Hi, " + name
✅ The modern way (Python 3.6+)आधुनिक तरीक़ा (Python 3.6+)现代写法(Python 3.6+)
Styleतरीक़ा写法Exampleउदाहरण示例
f-stringf"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
OUTPUT (YOUR NUMBERS WILL DIFFER)OUTPUT (आपके अंक अलग होंगे)OUTPUT(你的数字会不同)
f-string : 0.143 s per million .format(): 0.140 s per million % style : 0.086 s per million
⏱️
What the Timing Really ShowsTiming असल में क्या दिखाती है计时结果说明了什么

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 模块至今仍有意使用 % 风格的占位符。)


SectionSection第 10 节

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मतलब含义
\nNew lineनई line换行
\tTabTab制表符
\\A real backslashअसली backslash一个真正的反斜杠
\'Single quoteSingle quote单引号
\"Double quoteDouble quote双引号
\rCarriage return (rare)Carriage return (कम)回车(少见)
\0Null character (low-level data)Null character (low-level data)空字符(底层数据)
\u00e9Unicode 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
OUTPUT
Line 1 Line 2 Name: Asha She said "hi" It's fine C:\Users\Asha C:\Users\new_folder café π 😀 5 'C:\new'

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")
OUTPUT (SyntaxError)
File "s16b.py", line 1 print("C:\Users\new_folder") ^^^^^^^^^^^^^^^^^^^^^ SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
🔑
Windows Path Golden RuleWindows Path का सुनहरा नियमWindows 路径黄金法则

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))
OUTPUT
'Python' len = 6 | first code point = 80 'नमस्ते' len = 6 | first code point = 2344 '你好' len = 2 | first code point = 20320 '😀' len = 1 | first code point = 128512 A म 你 True True 90 97 ['Cherry', 'apple', 'banana'] ['apple', 'banana', 'Cherry']
🔤
Two Surprises Worth Knowingदो चौंकाने वाली बातें两个值得了解的意外

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。


SectionSection第 11 节

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)}")
OUTPUT
P y t h o n Index 0: P Index 1: y Index 2: t Index 3: h Index 4: o Index 5: n Vowel count: 6 Vowel count: 6

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。


SectionSection第 12 节

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()
OUTPUT
══════════════════════════════════════════════════ STRING ANALYSIS REPORT ══════════════════════════════════════════════════ Input: "Python is a POWERFUL programming languag..." Length: 60 characters Words: 9 Vowels: 18 Digits: 4 Spaces: 8 First word: Python Last word: 1991. Uppercase: PYTHON IS A POWERFUL PROGRAMMING LANGUAG Reversed: .1991 ni desaeler ,egaugnal gnimmargorp ══════════════════════════════════════════════════ Contains 'Python'? True Starts with 'Py'? True Ends with '.'? True Normalised: python is a powerful programming language, released in 1991.
🎯
Read the Report Line by LineReport को line-दर-line पढ़ें逐行读懂这份报告

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()) 整理空格。


SectionSection第 13 节

Golden Rules 🏆सुनहरे नियम 🏆黄金法则 🏆

🐍 Python Strings — 9 RulesPython Strings — 9 नियमPython 字符串 —— 9 条法则
1
Never try to change a string in place. s[0] = "X" raises TypeError. Build a new one: s = "X" + s[1:].
String को अपनी जगह बदलने की कोशिश न करें। s[0] = "X" TypeError देता है। नई बनाएँ: s = "X" + s[1:]।
永远不要尝试原地修改字符串。s[0] = "X" 会引发 TypeError。改为构建新的:s = "X" + s[1:]。
2
Methods return NEW strings. text.upper() does not change text. Write text = text.upper() to keep the result.
Methods नई strings लौटाते हैं। text.upper() text को नहीं बदलता। नतीजा रखने के लिए text = text.upper() लिखें।
方法返回新字符串。text.upper() 不会改变 text。要保留结果,写 text = text.upper()。
3
The slice stop is EXCLUSIVE. s[2:5] gives indexes 2, 3, 4 — the same rule as range().
Slice का stop शामिल नहीं होता। s[2:5] indexes 2, 3, 4 देता है — range() वाला ही नियम।
切片的 stop 不包含在内。s[2:5] 给出索引 2、3、4 —— 与 range() 规则相同。
4
Use f-strings for formatting. They are the clearest way to build text in Python 3.6+. You will still read % and .format() in older code.
Formatting के लिए f-strings लगाएँ। Python 3.6+ में text बनाने का यह सबसे साफ़ तरीक़ा है। पुराने code में % और .format() अब भी दिखेंगे।
格式化用 f-字符串。它是 Python 3.6+ 中构建文本最清晰的方式。在旧代码里你仍会看到 % 和 .format()。
5
Use raw strings for Windows paths and regex. r"C:\Users\Asha". Without the r, \n silently breaks the path and \U is a SyntaxError.
Windows paths और regex के लिए raw strings लगाएँ। r"C:\Users\Asha"। r के बिना \n path को चुपचाप तोड़ता है और \U SyntaxError है।
Windows 路径和正则表达式用原始字符串。r"C:\Users\Asha"。不加 r,\n 会悄悄破坏路径,\U 则是 SyntaxError。
6
Build long text with "".join(parts). Each + may copy the whole string so far, so a big loop of s += x can become slow. CPython sometimes optimises +=, but join() is fast everywhere.
लंबा text "".join(parts) से बनाएँ। हर + अब तक की पूरी string copy कर सकता है, इसलिए s += x वाला बड़ा loop धीमा हो सकता है। CPython कभी-कभी += को तेज़ कर देता है, पर join() हर जगह तेज़ है।
用 "".join(parts) 构建长文本。每次 + 都可能复制目前为止的整个字符串,所以大循环里的 s += x 可能变慢。CPython 有时会优化 +=,但 join() 在哪里都快。
7
Use in to check for text. "fox" in sentence is clearer than sentence.find("fox") != -1. Keep find() for when you need the position.
Text जाँचने के लिए in लगाएँ। "fox" in sentence sentence.find("fox") != -1 से साफ़ है। Position चाहिए तभी find() लगाएँ।
检查文本用 in。"fox" in sentence 比 sentence.find("fox") != -1 更清晰。需要位置时再用 find()。
8
Chain methods. text.strip().lower().replace(" ", "_") reads left to right like a pipeline. Each method returns a new string, so chaining is safe.
Methods को जोड़ें। text.strip().lower().replace(" ", "_") pipeline की तरह बाएँ से दाएँ पढ़ा जाता है। हर method नई string लौटाता है, इसलिए जोड़ना सुरक्षित है।
链式调用方法。text.strip().lower().replace(" ", "_") 像流水线一样从左往右读。每个方法都返回新字符串,所以链式调用是安全的。
9
Compare text with ==, never is. Interning is a CPython detail; two equal strings can be different objects.
Text की तुलना == से करें, is से कभी नहीं। Interning CPython की अंदरूनी बात है; दो बराबर strings अलग objects हो सकती हैं।
比较文本用 ==,绝不用 is。驻留是 CPython 的实现细节;两个相等的字符串可能是不同的对象。
LIVELIVE互动Quick Checkछोटी जाँच小测验

Six questions on strings. Pick an answer to see why.

Strings पर छह सवाल। जवाब चुनें और कारण देखें।

关于字符串的六道题。选择答案查看解释。

🧵
Key Takeawayमुख्य सीख核心要点

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-字符串格式化,用原始字符串处理反斜杠,用 == 进行比较。

🐍 Try Python Yourself

Write, run and visualize Python step by step. No install needed.