String.replace () jest przestarzałe w Pythonie 3.x. Jaki jest nowy sposób na zrobienie tego?
String.replace () jest przestarzałe w Pythonie 3.x. Jaki jest nowy sposób na zrobienie tego?
Odpowiedzi:
re.sub()
.
string
funkcje są przestarzałe. str
metody nie są.
'foo'.replace(...)
Metoda replace () w pythonie 3 jest używana po prostu przez:
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
Możesz użyć str.replace () jako łańcucha str.replace () . Myślisz, że masz ciąg znaków 'Testing PRI/Sec (#434242332;PP:432:133423846,335)'
i chcesz zastąpić cały '#',':',';','/'
znak znakiem '-'
. Możesz go wymienić w ten sposób (normalny sposób),
>>> 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)'
lub w ten sposób (chain of str.replace () )
>>> str = 'Testing PRI/Sec (#434242332;PP:432:133423846,335)'.replace('#', '-').replace(':', '-').replace(';', '-').replace('/', '-')
>>> str
'Testing PRI-Sec (-434242332-PP-432-133423846,335)'
Do Twojej wiadomości, dodając niektóre znaki do dowolnego słowa o ustalonej pozycji wewnątrz ciągu (np. Zmieniając przymiotnik na przysłówek poprzez dodanie przyrostka -ly ), możesz umieścić przyrostek na końcu wiersza, aby był czytelny. Aby to zrobić, użyj split()
wewnątrz 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')