Python में String Methods
In this page:
string.method_name(arguments)
# e.g. string.upper(), string.replace(old, new)
Case Conversions
.lower(), .upper(), और .title() letter casing को adjust करके एक नई string return करते हैं -- इनका इस्तेमाल आमतौर पर comparison के लिए user input को normalize करने में होता है, क्योंकि वरना "Yes" और "yes" को अलग strings माना जाएगा।
उदाहरण: Case Conversions
text = "Yes"
print(text.lower()) # "yes"
print(text.upper()) # "YES"
print(text.title()) # "Yes"
Whitespace हटाना
.strip() किसी string के शुरू और अंत के whitespace को हटाता है, जबकि .lstrip() और .rstrip() क्रमशः सिर्फ़ left या right side को trim करते हैं -- यह किसी user द्वारा paste या type किए गए text को साफ़ करने के लिए ज़रूरी है जिसमें कहीं spare spaces हो सकते हैं।
उदाहरण: Stripping Whitespace
text = " hello "
print(text.strip()) # removes whitespace from both ends
print(text.lstrip()) # removes whitespace from the left only
print(text.rstrip()) # removes whitespace from the right only
Substrings को Replace करना
.replace(old, new) किसी string में old के हर occurrence को ढूँढता है और उसे new से बदल देता है, modified copy return करते हुए -- यह input को sanitize करने या साधारण find-and-replace text transformations करने जैसे कामों के लिए उपयोगी है।
उदाहरण: Replacing Substrings
text = "I like cats"
print(text.replace("cats", "dogs"))
Splitting और Joining
.split() किसी string को जहाँ भी एक separator मिलता है (default रूप से whitespace) वहाँ तोड़कर substrings की एक list बनाता है, और .join() इसका उल्टा करता है, चुने गए separator से हर टुकड़े के बीच जोड़ते हुए strings की list को वापस जोड़ता है।
उदाहरण: Splitting and Joining
words = "a,b,c".split(",") # breaks the string into a list wherever a comma appears
print(words)
print("-".join(words)) # stitches the list back into a string, separated by "-"
Finding और Counting
.find() किसी substring को खोजता है और उसके पहले occurrence का index return करता है (या मौजूद न होने पर -1), जबकि .count() इसके बजाय यह बताता है कि वह substring string में कहीं भी कितनी बार आता है।
उदाहरण: Finding and Counting
text = "banana"
print(text.find("na")) # index of the first occurrence of "na"
print(text.count("a")) # how many times "a" appears
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: