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
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]=" "
CodePudding user response:
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.
CodePudding user response:
You seem to save the whitespaces as strings, but query them as integer. Try a[i] = "0"
and such.
CodePudding user response:
It doesn't work because you try to compare string with int values.
a[i] is string type range(0,9) is list with int values.
Try this:
for i in range(lenghtOfText):
if (int(a[i]) in range(0,9)):
a[i]=" "