Home > Blockchain >  How can ı replace the whitespace to random number in string
How can ı replace the whitespace to random number in string

Time:05-12

I am trying to change whitespaces to random number and number must be between the (0,9) in phyton ex. "hello world" to "hello6world" or "ı am the king" to "ı5am6the8king"

import random
text = input("Text :")
text.replace(" ", str((random.randint(0, 9))))
print(text)

here's my code but it didn't change the whitespace to number.

CodePudding user response:

For letter in myString: 
  If letter = ' ':
    #Replace with random

CodePudding user response:

text = input("Text :")
print(text.replace(" ", str((random.randint(0, 9)))))

The above code prints the replace query used as it will print the returned value of Text.replace()automatically.

If you print(Text) as in original code it will print the original string saved in the variable Text as strings are immutable. Instead you can also save text.replace(" ", str((random.randint(0, 9)))) in a different variable (let x) and then print(x).

Either directly printing the replace query or saving it in a different variable and printing it will solve the issue of filling whitespaces with integer.

*Though this will apply only the same random number generated to all the whitespaces such as making the string as "i5am5the5king" instead of "i5am6the8king".You can rectify this by traversing the string and assigning whitespaces as a randint to a new string by doing

import random
text = input("Text :")
x=""
for i in range(len(text)):
    if text[i]==" ":
        x =str((random.randint(0, 9)))
    else:
        x =text[i]
print(x)

This will print a string with whitespaces replaced as random numbers such as "i8am7the9king" instead of "i2am2the2king".

  • Related