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

前端 未结 4 1120
暗喜
暗喜 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 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()...

提交回复
热议问题