Python में String Operations
In this page:
string1 + string2
string * n
substring in string
len(string)
String Concatenation
+ operator strings को end to end जोड़कर एक नई string बनाता है; क्योंकि Python में strings immutable हैं, किसी loop में concatenate करना बार-बार नए objects बनाता है, यही वजह है कि बड़ी मात्रा में text के लिए कई टुकड़ों को ''.join(list) से जोड़ना ज़्यादा efficient idiom है।
उदाहरण: String Concatenation
first = "Hello"
second = "World"
print(first + " " + second) # + joins the strings end to end into a new string
String Repetition
किसी string को * से किसी integer के साथ multiply करना उसे उतनी ही बार repeat करता है, जो separators, padding, या '-' * 40 जैसे ASCII-art borders बनाने का एक जल्दी तरीका है, बिना कोई loop लिखे।
उदाहरण: String Repetition
print("-" * 10)
Membership Operators
in और 'not in' substring की मौजूदगी जाँचते हैं और एक boolean return करते हैं, जिससे ये ज़्यादा costly parsing करने से पहले membership test करने का सबसे simple तरीका बन जाते हैं -- उदाहरण के लिए किसी address को आगे validate करने की कोशिश करने से पहले '@' in email जाँचना।
उदाहरण: Membership Operators
email = "[email protected]"
print("@" in email)
Strings की Comparison
< और > जैसे comparison operators strings की तुलना character by character, Unicode code points का इस्तेमाल करके करते हैं, तो Apple < apple True है क्योंकि uppercase letters lowercase वालों से पहले sort होते हैं -- यह user input को पहले case normalize किए बिना sort करते समय bugs का एक आम कारण है।
उदाहरण: Comparing Strings
print("Apple" < "apple")
Strings पर Iterate करना
for loop से किसी string पर loop करना क्रम से एक बार में एक character visit करता है, जो vowels गिनने या range(len(s)) के ज़रिए index-based access के बिना character-frequency map बनाने जैसे कामों के लिए उपयोगी है।
उदाहरण: Iterating over Strings
for char in "cat":
print(char)
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: