I want to do this:
>>> special = \'x\'
>>> random_function(\'Hello how are you\')
\'xxxxx xxx xxx xxx\'
I basically want
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()
...