Replace part of a string in Python?

前端 未结 3 1301
鱼传尺愫
鱼传尺愫 2020-11-28 12:11

I used regular expressions to get a string from a web page and part of the string may contain something I would like to replace with something else. How would it be possible

相关标签:
3条回答
  • 2020-11-28 12:55

    You can easily use .replace() as also previously described. But it is also important to keep in mind that strings are immutable. Hence if you do not assign the change you are making to a variable, then you will not see any change. Let me explain by;

        >>stuff = "bin and small"
        >>stuff.replace('and', ',')
        >>print(stuff)
        "big and small" #no change
    

    To observe the change you want to apply, you can assign same or another variable;

        >>stuff = "big and small"
        >>stuff = stuff.replace("and", ",")   
        >>print(stuff)
        'big, small'
    
    0 讨论(0)
  • 2020-11-28 12:56

    Use the replace() method on string:

    >>> stuff = "Big and small"
    >>> stuff.replace( " and ", "/" )
    'Big/small'
    
    0 讨论(0)
  • 2020-11-28 13:04
    >>> stuff = "Big and small"
    >>> stuff.replace(" and ","/")
    'Big/small'
    
    0 讨论(0)
提交回复
热议问题