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

前端 未结 4 1130
暗喜
暗喜 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:41

    Not sure if I should add this in a comment or an entire answer? As someone else suggested, I would suggest using the regex but you can use the \w character to refer to any letter of the alphabet. Here's the full code:

      import re
    
     def random_function(string):
         newString=re.sub('\w', 'x', string) 
         return(newString)
    
     print(random_function('Hello how are you'))
    

    Should print xxxxx xxx xxx xxx

提交回复
热议问题