3

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.

4 Answers 4

4

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

Sign up to request clarification or add additional context in comments.

Comments

4

This can be easily done with regex:

>>> re.sub('[A-Za-z]', 'x', 'Hello how are you')
'xxxxx xxx xxx xxx'

Comments

2
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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.