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

前端 未结 4 1103
暗喜
暗喜 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

    This can be easily done with regex:

    >>> re.sub('[A-Za-z]', 'x', 'Hello how are you')
    'xxxxx xxx xxx xxx'
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-21 08:01

    Since strings in Python are immutable, each time you use the replace() method a new string has to be created. Each call to replace also has to loop through the entire string. This is obviously inefficient, albeit not noticeable on this scale.

    One alternate is to use a list comprehesion (docs, tutorial) to loop through the string once and create a list of the new characters. The isalnum() method can be used as a test to only replace alphanumeric characters (i.e., leave spaces, punctuation etc. untouched).

    The final step is to use the join() method to join the characters together into the new string. Note in this case we use the empty string '' to join the characters together with nothing in between them. If we used ' '.join(new_chars) there would be a space between each character, or if we used 'abc'.join(new_chars) then the letters abc would be between each character.

    >>> def random_function(string, replacement):
    ...     new_chars = [replacement if char.isalnum() else char for char in string]
    ...     return ''.join(new_chars)
    ...
    >>> random_function('Hello how are you', 'x')
    'xxxxx xxx xxx xxx'
    

    Of course, you should probably give this function a more logical name than random_function()...

    0 讨论(0)
提交回复
热议问题