How to replace a string in a function with another string in Python?

前端 未结 4 1131
暗喜
暗喜 2020-12-21 07:23

I want to do this:

>>> special = \'x\'
>>> random_function(\'Hello how are you\')
\'xxxxx xxx xxx xxx\'

I basically want

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-21 07:53

    def hide(string, replace_with):
        for char in string:
            if char not in " !?.:;":  # chars you don't want to replace
                string = string.replace(char, replace_with) # replace char by char
        return string
    
    print hide("Hello how are you", "x")
    'xxxxx xxx xxx xxx'
    

    Also check out the string and re modules.

提交回复
热议问题