String.replace () को अजगर 3.x पर दर्शाया गया है। ऐसा करने का नया तरीका क्या है?
String.replace () को अजगर 3.x पर दर्शाया गया है। ऐसा करने का नया तरीका क्या है?
जवाबों:
जैसे 2.x में, उपयोग करें str.replace()।
उदाहरण:
>>> 'Hello world'.replace('world', 'Guido')
'Hello Guido'
re.sub()।
stringफ़ंक्शंस को हटा दिया गया है। strविधियाँ नहीं हैं।
'foo'.replace(...)
पाइथन 3 में प्रतिस्थापित () विधि का उपयोग केवल इसके द्वारा किया जाता है:
a = "This is the island of istanbul"
print (a.replace("is" , "was" , 3))
#3 is the maximum replacement that can be done in the string#
>>> Thwas was the wasland of istanbul
# Last substring 'is' in istanbul is not replaced by was because maximum of 3 has already been reached
आप उपयोग कर सकते हैं str.replace () एक के रूप में की श्रृंखला str.replace () । सोचें कि आपके पास एक स्ट्रिंग है 'Testing PRI/Sec (#434242332;PP:432:133423846,335)'और आप सभी '#',':',';','/'चिन्ह को बदलना चाहते हैं '-'। आप इसे इस तरह से बदल सकते हैं (सामान्य तरीका),
>>> str = 'Testing PRI/Sec (#434242332;PP:432:133423846,335)'
>>> str = str.replace('#', '-')
>>> str = str.replace(':', '-')
>>> str = str.replace(';', '-')
>>> str = str.replace('/', '-')
>>> str
'Testing PRI-Sec (-434242332-PP-432-133423846,335)'
या इस तरह ( str.replace () की श्रृंखला )
>>> str = 'Testing PRI/Sec (#434242332;PP:432:133423846,335)'.replace('#', '-').replace(':', '-').replace(';', '-').replace('/', '-')
>>> str
'Testing PRI-Sec (-434242332-PP-432-133423846,335)'
FYI करें, जब कुछ पात्रों को मनमाने ढंग से, स्ट्रिंग के अंदर स्थिति-निश्चित शब्द (जैसे प्रत्यय- ऐड जोड़कर एक विशेषण में विशेषण बदलते हुए ) में जोड़ा जाता है , तो आप प्रत्यय को पठनीयता के लिए लाइन के अंत में रख सकते हैं। ऐसा करने के लिए, split()अंदर का उपयोग करें replace():
s="The dog is large small"
ss=s.replace(s.split()[3],s.split()[3]+'ly')
ss
'The dog is largely small'
ss = s.replace(s.split()[1], +s.split()[1] + 'gy')
# should have no plus after the comma --i.e.,
ss = s.replace(s.split()[1], s.split()[1] + 'gy')