PGDCA, BCA, B-Tech, MCA, M-Tech, B.Sc computer science राजस्थान सूचना सहायक व कंप्यूटर शिक्षक विशेष नोट्स: इस अध्याय में हम Python String Methods: upper, lower, strip, split, join, replace (स्ट्रिंग मेथड्स: upper(), lower(), strip(), split(), join() और replace()) की संपूर्ण थ्योरी, मुख्य तकनीकी बिंदु, तुलनात्मक तालिका और विगत परीक्षाओं के पैटर्न पर आधारित 20 अति-महत्वपूर्ण बहुविकल्पीय प्रश्न (MCQs) विस्तृत हिंदी व अंग्रेजी व्याख्या सहित पढ़ेंगे।
Overview: Python string methods such as upper(), lower(), strip(), split(), join(), and replace() always return a new string or list without mutating the original immutable str. Key exam traps include strip(chars) treating its argument as a character set rather than a prefix/suffix, split() vs split(' ') handling whitespace differently, and join() being called on the separator string.
अध्याय सार: पायथन के स्ट्रिंग मेथड्स जैसे upper(), lower(), strip(), split(), join() और replace() मूल इम्यूटेबल स्ट्रिंग को बदले बिना हमेशा एक नई स्ट्रिंग या लिस्ट लौटाते हैं। परीक्षा के मुख्य बिंदु: strip(chars) अक्षरों के समूह पर काम करता है, split() और split(' ') अलग व्यवहार करते हैं, तथा join() को सेपरेटर स्ट्रिंग पर कॉल किया जाता है।
Python String Methods: upper, lower, strip, split, join, replace: Detailed Notes & Architecture (स्ट्रिंग मेथड्स: upper(), lower(), strip(), split(), join() और replace())
1. Case Conversion Methods: upper, lower, title, capitalize, casefold (केस परिवर्तन मेथड्स: upper, lower, title, capitalize, casefold)
[EN] Because strings are immutable, case methods return transformed copies while leaving the source variable unchanged unless reassigned (s = s.upper()). upper() and lower() convert all cased characters to uppercase or lowercase; swapcase() flips cases; capitalize() uppercases index 0 and lowercases the rest; and title() uppercases the first letter of each word (note: apostrophes act as word breaks, turning "they're" into "They'Re"). For case-insensitive Unicode comparison, casefold() is stronger than lower()—for example, German 'ß'.casefold() produces 'ss'.
[HI] स्ट्रिंग इम्यूटेबल होने के कारण ये सभी मेथड मूल वेरिएबल को बदले बिना नई कॉपी लौटाते हैं। upper() सभी अक्षरों को बड़े और lower() छोटे अक्षरों में बदलता है; capitalize() केवल पहले अक्षर को बड़ा और बाकी को छोटा करता है; title() प्रत्येक शब्द का पहला अक्षर बड़ा करता है (ध्यान दें: 'they\'re'.title() से 'They\'Re' बनता है)। यूनिकोड केस-रहित तुलना के लिए casefold() मेथड lower() से अधिक प्रभावी होता है।
2. Whitespace & Character-Set Trimming: strip, lstrip, rstrip (व्हाइटस्पेस और अक्षर-समूह हटाना: strip, lstrip, rstrip)
[EN] Called with no arguments, strip() removes all leading and trailing whitespace characters (' ', '\t', '\n', '\r'), while lstrip() trims only the left end and rstrip() only the right end. Crucially, when passed a string argument like s.strip(chars), Python treats chars as an unordered SET of characters to strip from both ends until hitting a character not in chars—NOT as a literal substring! For example, 'www.example.com'.lstrip('w.') strips all leading 'w' and '.' characters leaving 'example.com', whereas 'ababa'.strip('ab') yields ''; to strip an exact prefix/suffix, use Python 3.9+'s removeprefix() and removesuffix().
[HI] बिना आर्ग्युमेंट के strip() दोनों सिरों से सभी व्हाइटस्पेस हटाता है, जबकि lstrip() केवल बाएँ और rstrip() केवल दाएँ सिरे से हटाता है। अत्यंत महत्वपूर्ण नियम: s.strip(chars) में chars को एक सबस्ट्रिंग नहीं बल्कि अक्षरों का सेट (character set) माना जाता है; अतः यह दोनों सिरों से उस सेट का हर अक्षर हटाता जाता है जब तक कोई अलग अक्षर न मिले। जैसे 'ababa'.strip('ab') से '' आता है; सटीक उपसर्ग/प्रत्यय हटाने के लिए पायथन 3.9+ के removeprefix() और removesuffix() का प्रयोग करें।
3. Tokenizing and Concatenating: split(), rsplit(), and join() (स्ट्रिंग तोड़ना और जोड़ना: split(), rsplit() और join())
[EN] Calling s.split() with no separator splits on arbitrary runs of consecutive whitespace and strips leading/trailing spaces (so ' a b '.split() -> ['a', 'b'], and ' '.split() -> []). In contrast, passing an explicit delimiter s.split(',') splits strictly at every comma, preserving empty tokens ('a,,b'.split(',') -> ['a', '', 'b'] and ''.split(',') -> ['']), and passing an empty separator s.split('') raises ValueError. The inverse method sep.join(iterable) is invoked on the separator string (not the list!), running in O(N) linear time; every element in the iterable must already be a str or TypeError is raised.
[HI] बिना सेपरेटर के s.split() लगातार खाली स्थानों पर स्ट्रिंग को तोड़ता है और किनारों के स्पेस हटा देता है (अतः ' a b '.split() -> ['a', 'b'] और ' '.split() -> [])। परंतु स्पष्ट सेपरेटर s.split(',') देने पर यह हर कॉमा पर तोड़ता है और खाली स्ट्रिंग ('') भी रखता है; सेपरेटर '' देने पर ValueError आता है। जोड़ने के लिए sep.join(iterable) को सेपरेटर पर कॉल किया जाता है; इटरेबल का प्रत्येक तत्व str होना आवश्यक है अन्यथा TypeError आता है।
4. Substitution and Search: replace, find vs index, startswith (प्रतिस्थापन और खोज: replace, find बनाम index, startswith)
[EN] s.replace(old, new, count=-1) returns a copy with all occurrences (or at most count occurrences from left to right) of old replaced by new. Interestingly, s.replace('', '-') inserts '-' before, between, and after every character ('ab'.replace('', '-') -> '-a-b-'). For searching, find(sub) returns the lowest index or -1 if absent, whereas index(sub) raises ValueError when missing; startswith() and endswith() accept either a single string or a tuple of candidate prefixes/suffixes.
[HI] s.replace(old, new, count) बाएँ से दाएँ old की सभी (या अधिकतम count) आवृत्तियों को new से बदलकर नई स्ट्रिंग लौटाता है। रोचक बात यह है कि s.replace('', '-') हर अक्षर के बीच व किनारों पर '-' जोड़ देता है ('ab'.replace('', '-') -> '-a-b-')। खोज के लिए find() न मिलने पर -1 लौटाता है जबकि index() ValueError देता है; startswith()/endswith() एक स्ट्रिंग या टपल स्वीकार करते हैं।
Syntax, Formula & Technical Example (Python String Methods: upper, lower, strip, split, join, replace)
raw = ' Python,Java,C++ '
clean = raw.strip().upper()
print(clean) # PYTHON,JAVA,C++
parts = raw.strip().split(',')
print(parts) # ['Python', 'Java', 'C++']
print(' | '.join(parts)) # Python | Java | C++
print('banana'.replace('a', 'o', 2)) # bonona
print('xxabcyy'.strip('xy')) # abc
Python String Methods: upper, lower, strip, split, join, replace Quick Reference & Comparison Table
| Method | Signature & Return Type | Key Exam Fact |
|---|---|---|
| strip([chars]) | Returns trimmed str copy | Removes char set from ends, not substring |
| split([sep, max]) | Returns list of str tokens | split() ignores blanks; split(' ') keeps them |
| sep.join(iter) | Returns single joined str | Called on separator; all items must be str |
| replace(old, new[, n]) | Returns str with replacements | Optional count n limits from left |
Python String Methods: upper, lower, strip, split, join, replace Top 20 Bilingual MCQs with Answers
Q1. What is the output of: s = 'python'; s.upper(); print(s)?
(s = 'python'; s.upper(); print(s) का आउटपुट क्या होगा?)
(A) python
(B) Python
(C) None
(D) PYTHON
Correct Answer: (A)
[EN] Strings are immutable and s.upper() returns a new uppercase string without modifying s in-place; the result was not reassigned.
[HI] स्ट्रिंग इम्यूटेबल है और s.upper() के मान को वापस s में असाइन नहीं किया गया, इसलिए s मूल 'python' ही रहेगा।
Q2. What is the output of: print('www.computersir.in'.lstrip('w.'))?
(print('www.computersir.in'.lstrip('w.')) का आउटपुट क्या होगा?)
(A) computersir.in
(B) ww.computersir.in
(C) www.computersir.in
(D) omputersir.in
Correct Answer: (A)
[EN] lstrip('w.') strips all leading characters belonging to the set {'w', '.'}, removing 'www.' until reaching 'c'.
[HI] lstrip('w.') बाएँ सिरे से {'w', '.'} समूह के सभी अक्षरों ('www.') को हटा देता है जब तक 'c' न आ जाए।
Q3. What does ' a b '.split() return versus ' a b '.split(' ')?
(' a b '.split() और ' a b '.split(' ') क्रमशः क्या लौटाते हैं?)
(A) ['a', 'b'] and ['a', 'b']
(B) ['', 'a', 'b', ''] and ['a', 'b']
(C) Raises ValueError on split(' ')
(D) ['a', 'b'] and ['', '', 'a', '', '', 'b', '', '']
Correct Answer: (D)
[EN] split() with no args collapses whitespace runs and strips ends; split(' ') splits strictly on every single space character.
[HI] बिना आर्ग्युमेंट के split() अतिरिक्त स्पेस समेट लेता है, जबकि split(' ') प्रत्येक सिंगल स्पेस पर अलग से तोड़ता है।
Q4. What happens when you execute '-'.join([1, 2, 3])?
('-'.join([1, 2, 3]) चलाने पर क्या होता है?)
(A) Returns '1-2-3'
(B) Raises ValueError
(C) Returns ['1-2-3']
(D) Raises TypeError
Correct Answer: (D)
[EN] str.join() requires every element of the iterable to be a str (or bytes-like matching type); ints raise TypeError.
[HI] str.join() के लिए इटरेबल के सभी तत्वों का str होना जरूरी है; int होने पर TypeError आता है।
Q5. What is the output of: print('mississippi'.replace('s', 'z', 2))?
(print('mississippi'.replace('s', 'z', 2)) का आउटपुट क्या होगा?)
(A) missizzippi
(B) mizziss
(C) mizzissippi
(D) mizzizzippi
Correct Answer: (C)
[EN] The optional third argument count=2 replaces only the first two occurrences from left to right.
[HI] तीसरा आर्ग्युमेंट count=2 बाएँ से दाएँ केवल पहले दो 's' को ही 'z' से बदलता है।
Q6. What does 'a,b,c,d'.split(',', 2) return?
('a,b,c,d'.split(',', 2) क्या मान लौटाता है?)
(A) ['a', 'b', 'c', 'd']
(B) ['a,b', 'c', 'd']
(C) ['a', 'b']
(D) ['a', 'b', 'c,d']
Correct Answer: (D)
[EN] maxsplit=2 performs at most 2 splits from the left, producing 3 elements in the returned list.
[HI] maxsplit=2 बाएँ से अधिकतम 2 बार विभाजन करता है, जिससे कुल 3 तत्वों की लिस्ट ['a', 'b', 'c,d'] बनती है।
Q7. Which error is raised by 'abc'.split('')?
('abc'.split('') चलाने पर कौन सा एरर आता है?)
(A) ValueError
(B) SyntaxError
(C) Returns ['a', 'b', 'c']
(D) TypeError
Correct Answer: (A)
[EN] Passing an empty separator '' to split() raises ValueError: empty separator (use list('abc') to split into characters).
[HI] split('') में खाली सेपरेटर देने पर ValueError: empty separator आता है।
Q8. What is the difference between s.find('x') and s.index('x') when 'x' is not in s?
(जब 'x' स्ट्रिंग s में न हो, तो s.find('x') और s.index('x') में क्या अंतर है?)
(A) Both return -1
(B) find() returns -1 whereas index() raises ValueError
(C) find() returns None whereas index() raises KeyError
(D) find() raises ValueError whereas index() returns -1
Correct Answer: (B)
[EN] find() signals absence safely by returning -1, while index() raises ValueError: substring not found.
[HI] न मिलने पर find() सुरक्षित रूप से -1 लौटाता है, जबकि index() ValueError उत्पन्न करता है।
Q9. What is the output of: print('ababa'.strip('ab'))?
(print('ababa'.strip('ab')) का आउटपुट क्या होगा?)
(A) 'aba'
(B) 'b'
(C) '' (empty string)
(D) 'a'
Correct Answer: (C)
[EN] Every character in 'ababa' belongs to the character set {'a', 'b'}, so strip('ab') removes all characters leaving ''.
[HI] 'ababa' का हर अक्षर {'a', 'b'} सेट में है, इसलिए strip('ab') सभी अक्षर हटाकर खाली स्ट्रिंग '' लौटाता है।
Q10. What does 'hello world'.title() vs 'hello world'.capitalize() return?
('hello world'.title() और 'hello world'.capitalize() क्या लौटाते हैं?)
(A) 'HELLO WORLD' and 'Hello world'
(B) 'Hello World' and 'Hello World'
(C) 'Hello world' and 'Hello World'
(D) 'Hello World' and 'Hello world'
Correct Answer: (D)
[EN] title() capitalizes the first letter of every word, whereas capitalize() uppercases only index 0 and lowercases the rest.
[HI] title() हर शब्द का पहला अक्षर बड़ा करता है, जबकि capitalize() केवल पहली शुरुआत का पहला अक्षर बड़ा करता है।
Q11. Which Python 3.9+ string method removes an exact prefix string rather than a character set?
(पायथन 3.9+ का कौन सा मेथड अक्षर-समूह के बजाय सटीक उपसर्ग (prefix) स्ट्रिंग हटाता है?)
(A) cutleft()
(B) trimprefix()
(C) lstrip()
(D) removeprefix()
Correct Answer: (D)
[EN] str.removeprefix(prefix) removes an exact leading substring if present, avoiding the character-set surprise of lstrip().
[HI] str.removeprefix(prefix) अक्षर-समूह के बजाय केवल सटीक शुरुआती उपसर्ग को ही हटाता है।
Q12. What is the output of: print('ab'.replace('', '-'))?
(print('ab'.replace('', '-')) का आउटपुट क्या होगा?)
(A) Raises ValueError
(B) ab
(C) a-b
(D) -a-b-
Correct Answer: (D)
[EN] Replacing the empty string '' inserts the replacement string before, between, and after every character of the string.
[HI] खाली स्ट्रिंग '' को प्रतिस्थापित करने पर '-' प्रत्येक अक्षर के पहले, बीच में और अंत में जुड़ जाता है।
Q13. What does ''.join(['P', 'y', '3']) return?
(''.join(['P', 'y', '3']) क्या मान लौटाता है?)
(A) ['Py3']
(B) Raises ValueError
(C) 'Py3'
(D) 'P y 3'
Correct Answer: (C)
[EN] Joining with the empty string '' concatenates all string items tightly with no separator between them.
[HI] खाली सेपरेटर '' से join() करने पर सभी स्ट्रिंग्स बिना किसी रिक्त स्थान के जुड़कर 'Py3' बनाती हैं।
Q14. What is the return type of 'file.py'.endswith(('.py', '.txt'))?
('file.py'.endswith(('.py', '.txt')) का रिटर्न प्रकार और मान क्या है?)
(A) TypeError (tuple not allowed)
(B) bool (True)
(C) bool (False)
(D) str ('.py')
Correct Answer: (B)
[EN] Both startswith() and endswith() accept a tuple of strings and return True if any element matches.
[HI] startswith() और endswith() दोनों स्ट्रिंग्स का टपल स्वीकार करते हैं और किसी से भी मिलान होने पर True लौटाते हैं।
Q15. What does 'one two three four'.rsplit(' ', 1) return?
('one two three four'.rsplit(' ', 1) क्या लौटाता है?)
(A) ['four', 'three', 'two', 'one']
(B) ['one', 'two three four']
(C) ['one two', 'three four']
(D) ['one two three', 'four']
Correct Answer: (D)
[EN] rsplit(sep, 1) performs 1 split starting from the right end of the string.
[HI] rsplit(' ', 1) दाएँ सिरे से केवल 1 बार विभाजन करता है, जिससे ['one two three', 'four'] मिलता है।
Q16. Which of the following statements about Python string methods is NOT true?
(पायथन स्ट्रिंग मेथड्स के बारे में निम्नलिखित में से कौन सा कथन सत्य नहीं है?)
(A) Calling s.replace('a', 'b') modifies the string object s in-place
(B) sep.join(words) raises TypeError if words contains integers
(C) s.strip('xy') removes both 'x' and 'y' in any order from both ends of s
(D) s.split() with no arguments returns an empty list [] for a whitespace-only string
Correct Answer: (A)
[EN] Because str is immutable, no string method ever modifies s in-place; replace() always returns a newly allocated str.
[HI] स्ट्रिंग इम्यूटेबल होने के कारण कोई भी स्ट्रिंग मेथड मूल स्ट्रिंग को इन-प्लेस नहीं बदलता; replace() हमेशा नई स्ट्रिंग लौटाता है।
Q17. Within Python String Methods: upper, lower, strip, split, join, replace, which method directly maps to: "Returns trimmed str copy"?
(Python String Methods: upper, lower, strip, split, join, replace में कौन सा Method सीधे "Returns trimmed str copy" से संबंधित है?)
(A) sep.join(iter)
(B) strip([chars])
(C) split([sep, max])
(D) replace(old, new[, n])
Correct Answer: (B)
[EN] In Python String Methods: upper, lower, strip, split, join, replace, 'strip([chars])' handles 'Returns trimmed str copy' (Removes char set from ends, not substring).
[HI] Python String Methods: upper, lower, strip, split, join, replace में 'strip([chars])' का कार्य/विवरण 'Returns trimmed str copy' (Removes char set from ends, not substring) है।
Q18. Which option accurately describes 'split([sep, max])' in Python String Methods: upper, lower, strip, split, join, replace?
(Python String Methods: upper, lower, strip, split, join, replace के संदर्भ में 'split([sep, max])' की सही विशेषता कौन सी है?)
(A) Returns str with replacements
(B) Returns list of str tokens
(C) Returns single joined str
(D) Returns trimmed str copy
Correct Answer: (B)
[EN] 'split([sep, max])' provides 'Returns list of str tokens' — key point: split() ignores blanks; split(' ') keeps them.
[HI] 'split([sep, max])' का मुख्य विवरण 'Returns list of str tokens' है (split() ignores blanks; split(' ') keeps them)।
Q19. In Python String Methods: upper, lower, strip, split, join, replace, identify the correct parameter for the specification: "Returns single joined str".
(Python String Methods: upper, lower, strip, split, join, replace में "Returns single joined str" विवरण किस विकल्प के लिए सही है?)
(A) strip([chars])
(B) split([sep, max])
(C) replace(old, new[, n])
(D) sep.join(iter)
Correct Answer: (D)
[EN] 'sep.join(iter)' corresponds to 'Returns single joined str' (Called on separator; all items must be str).
[HI] 'sep.join(iter)' का संबंध 'Returns single joined str' (Called on separator; all items must be str) से है।
Q20. Considering Python String Methods: upper, lower, strip, split, join, replace, what key behavior defines 'replace(old, new[, n])'?
(Python String Methods: upper, lower, strip, split, join, replace में 'replace(old, new[, n])' की मुख्य भूमिका या मान क्या है?)
(A) Returns single joined str
(B) Returns trimmed str copy
(C) Returns list of str tokens
(D) Returns str with replacements
Correct Answer: (D)
[EN] 'replace(old, new[, n])' represents 'Returns str with replacements' (Optional count n limits from left).
[HI] 'replace(old, new[, n])' का अर्थ/मान 'Returns str with replacements' है (Optional count n limits from left)।
Python String Methods: upper, lower, strip, split, join, replace — Exam FAQs
Q1: Why is join() written as ','.join(items) instead of items.join(',')?
join() को items.join(',') के बजाय ','.join(items) क्यों लिखा जाता है?
[EN] Because join() works on ANY iterable (lists, tuples, sets, generators), not just lists. Putting join() on str keeps every iterable type clean while guaranteeing a str return value.
[HI] क्योंकि join() केवल लिस्ट पर नहीं बल्कि टपल, सेट और जनरेटर जैसे किसी भी इटरेबल पर काम करता है; इसे str क्लास में रखने से आउटपुट हमेशा str मिलता है।
Q2: Why did 'test.py'.rstrip('.py') return 'test' while 'happy.py'.rstrip('.py') returned 'ha'?
'test.py'.rstrip('.py') ने 'test' दिया लेकिन 'happy.py'.rstrip('.py') ने 'ha' क्यों दिया?
[EN] Because rstrip('.py') treats '.py' as the character set {'.', 'p', 'y'} and strips the 'p', 'p', and 'y' at the end of 'happy' too! Use 'happy.py'.removesuffix('.py') in Python 3.9+ instead.
[HI] क्योंकि rstrip('.py') अक्षरों के सेट {'.', 'p', 'y'} पर काम करता है और 'happy' के अंत के 'ppy' भी हटा देता है। सटीक प्रत्यय हटाने के लिए removesuffix('.py') प्रयोग करें।
Q3: Is ''.join(list_of_strings) faster than concatenating with += in a loop?
क्या लूप में += की तुलना में ''.join(list_of_strings) अधिक तेज है?
[EN] Yes. Loop concatenation repeatedly allocates new intermediate strings (up to O(n^2) in general), whereas str.join() computes total length in one pass and builds the final string in O(n) time.
[HI] हाँ। लूप में += बार-बार नई स्ट्रिंग बनाता है, जबकि str.join() एक ही बार में कुल आकार गिनकर O(n) समय में पूरी स्ट्रिंग बना देता है।
Post a Comment
Post a Comment