How to use string.replace() in python 3.x

后端 未结 8 1849
旧巷少年郎
旧巷少年郎 2020-11-22 12:29

The string.replace() is deprecated on python 3.x. What is the new way of doing this?

8条回答
  •  春和景丽
    2020-11-22 12:55

    You can use str.replace() as a chain of str.replace(). Think you have a string like 'Testing PRI/Sec (#434242332;PP:432:133423846,335)' and you want to replace all the '#',':',';','/' sign with '-'. You can replace it either this way(normal way),

    >>> 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)'
    

    or this way(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)'
    

提交回复
热议问题