Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I want to do this:

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

I basically want to return the string: {(str) -> str}

I keep on getting variables undefined.

Sorry this is my first post.

like image 886
UberNate Avatar asked Aug 01 '26 21:08

UberNate


2 Answers

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()...

like image 128
Blair Avatar answered Aug 04 '26 11:08

Blair


This can be easily done with regex:

>>> re.sub('[A-Za-z]', 'x', 'Hello how are you')
'xxxxx xxx xxx xxx'
like image 31
JBernardo Avatar answered Aug 04 '26 12:08

JBernardo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!