Reputation: 115
I'm writing a program in python 3 to convert input string to integers. There is just one problem with the code. That whenever a space comes it prints -64. I've tried editing a code but it prints -64 along with the space. Any advice?
n = input("please enter the text:").lower()
print(n)
a = []
for i in n:
a.append(ord(i)-96)
if (ord(i)-96) == -64:
a.append(" ")
print(a)
Thanks
Input: "BatMan is Awesome"
Output: [2, 1, 20, 13, 1, 14, -64, ' ', 9, 19, -64, ' ', 1, 23, 5, 19, 15, 13, 5]
Upvotes: 0
Views: 85
Reputation: 1018
You could also do this as a one(ish)-liner:
import string
n = input("please enter the text:").lower()
a = [ord(c) - 96 if c not in string.whitespace else c for c in n]
print(a)
Using the string.whitespace list also means that other types of whitespace will be kept, which might be useful to you?
Upvotes: 1
Reputation: 180411
You can check if the character is a space
with str.isspace() adding ord(i)-96
if it not a space else just add the char:
n = "BatMan is Awesome".lower()
print([ord(i)-96 if not i.isspace() else i for i in n])
[2, 1, 20, 13, 1, 14, ' ', 9, 19, ' ', 1, 23, 5, 19, 15, 13, 5]
The equivalent code in your loop would be:
a = []
for i in n:
if not i.isspace():
a.append(ord(i)-96)
else:
a.append(i)
Upvotes: 2
Reputation: 22954
Actually you were appending ord(i)-96
to a
before checking the condition if (ord(i)-96) == -64
, So the correct way is to first check the condition and if it matches then append " "
else simple append ord(i)-96
, You can simply do the same with only one if condition and ignoring the else cause by reverting the conditional as :
n = input("please enter the text:").lower()
print(n)
a = []
for i in n:
if (ord(i)-96) != -64:
a.append(ord(i)-96)
print(a)
Upvotes: 1
Reputation: 7384
If I understand you correctly you want to convert "abc def"
to [1, 2, 3, " ", 4, 5, 6]
. Currently you are first adding ord(i) - 96
to your list and then, if the character is a space, you add an additional space. You want only to add ord(i) - 96
if it is not a space.
n = input("please enter the text:").lower()
print(n)
a = []
for i in n:
if (ord(i)-96) == -64:
a.append(" ")
else:
a.append(ord(i)-96)
print(a)
Upvotes: 2