El string.replace () está en desuso en python 3.x. ¿Cuál es la nueva forma de hacer esto?
El string.replace () está en desuso en python 3.x. ¿Cuál es la nueva forma de hacer esto?
Respuestas:
re.sub(),.
stringfunciones están en desuso. strLos métodos no lo son.
'foo'.replace(...)
El método replace () en python 3 se usa simplemente por:
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
Puede usar str.replace () como una cadena de str.replace () . Piensa que tiene una cadena como 'Testing PRI/Sec (#434242332;PP:432:133423846,335)'y desea reemplazar todo el '#',':',';','/'signo con '-'. Puede reemplazarlo de esta manera (forma normal),
>>> 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)'
o de esta manera (cadena de str.replace () )
>>> str = 'Testing PRI/Sec (#434242332;PP:432:133423846,335)'.replace('#', '-').replace(':', '-').replace(';', '-').replace('/', '-')
>>> str
'Testing PRI-Sec (-434242332-PP-432-133423846,335)'
Para su información, al agregar algunos caracteres a una palabra arbitraria, fija en la posición dentro de la cadena (por ejemplo, cambiar un adjetivo a un adverbio agregando el sufijo -ly ), puede colocar el sufijo al final de la línea para facilitar la lectura. Para hacer esto, use split()adentro 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')