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

后端 未结 8 1760
旧巷少年郎
旧巷少年郎 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:33

    replace() is a method of <class 'str'> in python3:

    >>> 'hello, world'.replace(',', ':')
    'hello: world'
    
    0 讨论(0)
  • 2020-11-22 12:37

    Try this:

    mystring = "This Is A String"
    print(mystring.replace("String","Text"))
    
    0 讨论(0)
  • 2020-11-22 12:39
    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')
    
    0 讨论(0)
  • 2020-11-22 12:43

    Simple Replace:         .replace(old, new, count) .

    text = "Apples taste Good."
    print(text.replace('Apples', 'Bananas'))          # use .replace() on a variable
    Bananas taste Good.          <---- Output
    
    print("Have a Bad Day!".replace("Bad","Good"))    # Use .replace() on a string
    Have a Good Day!             <----- Output
    
    print("Mom is happy!".replace("Mom","Dad").replace("happy","angry"))  #Use many times
    Dad is angry!                <----- Output
    
    0 讨论(0)
  • 2020-11-22 12:50

    The replace() method in python 3 is used simply by:

    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
    
    0 讨论(0)
  • 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)'
    
    0 讨论(0)
提交回复
热议问题