Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can ı replace the number to white space in python

I have a encrypt decrypt work in phyton, first ı am changed the whitespaces to random numbers. In order to do this job, I converted the string into a list with this code a = [x for x in text] . ı replaced the whitespaces using this code :

    for i in range(lenghtOfText):
        if ( a[i]==" "):
            a[i]=str((random.randint(0, 9)))

now ı need one more time change the numbers with whitespaces. ı tried this but itsn’t work

    for i in range(lenghtOfText):
        if (a[i] in range(0,9)):
            a[i]=" "

I tried one more way for the do this. but it’s still not work. the other code is

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    for i in range(lenghtOfText):
        if (a[i] == 0 or a[i] == 1 or a[i] == 2 or a[i] == 3 or a[i] == 4  or a[i] == 5 or a[i] == 6 or a[i] == 7 or a[i] == 8 or a[i] == 9 ):
            a[i]=" "

>Solution :

That’s because the character '1' (ascii 49) is not the same as the number 1.

Try this:

for i in range(lenghtOfText):
    try:
        if (int(a[i]) in range(0,10)):
            a[i]=" "
    except:
        pass

Note: Remember range’s end is EXCLUSIVE.

Slightly better way:

digits = [str(i) for i in range(10)]
for i in range(lenghtOfText):
    if a[i] in digits:
        a[i] = " "

Even better:

for i in range(lenghtOfText):
    if a[i].isdigit():
        a[i] = " "

One more, this time using map:

a = list(map(lambda e: " " if e.isdigit() else e, a))

The only caveat is that this will create a copy of the array, leaving the original one unmodified.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading