0

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] 
3
  • 2
    Can you provide some sample inputs and your expected output? Commented May 14, 2015 at 11:46
  • @Cyber: Done, added an input and the output Commented May 14, 2015 at 11:50
  • @Cyber a code but it prints -64 along with the space Commented May 14, 2015 at 11:51

4 Answers 4

2

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) 
Sign up to request clarification or add additional context in comments.

1 Comment

Cheers man. It worked perfectly. Yes I made that stupid mistake of adding first and conditioning later. Thanks
2

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) 

2 Comments

Doh! I was 3 minutes too slow!
Thanks boss, helps a lot.
1

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) 

Comments

1

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?

1 Comment

Thanks boss! Appreciate it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.