2015-05-14 63 views
0

我正在写一个程序在python 3将输入字符串转换为整数。代码只有一个问题。只要有空间,它就会打印-64。我试过编辑一个代码,但是它打印了64个空格。有什么建议?打印字符串作为整数在python 3

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) 

感谢

Input: "BatMan is Awesome" 
Output: [2, 1, 20, 13, 1, 14, -64, ' ', 9, 19, -64, ' ', 1, 23, 5, 19, 15, 13, 5] 
+2

您能提供一些样本输入和您的预期输出吗? – CoryKramer

+0

@Cyber​​:完成,添加了一个输入和输出 – pythonnewbie

+0

@Cyber​​ *一个代码,但它打印64与空间* – ZdaR

回答

2

如果我理解你正确地要"abc def"转换为[1, 2, 3, " ", 4, 5, 6]。目前,您首先将ord(i) - 96添加到列表中,然后,如果角色是空格,则需要添加额外的空间。如果不是空格,只需要添加ord(i) - 96

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) 
+0

干杯的人。它工作完美。是的,我犯了一个愚蠢的错误,即先添加和调节。谢谢 – pythonnewbie

1

其实你检查条件if (ord(i)-96) == -64前追加ord(i)-96a,所以正确的做法是,先检查车况,如果匹配,则追加" "其他简单的追加ord(i)-96,你可以简单地做同样的唯一一个if条件,并通过恢复条件为忽略其他原因:

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) 
+0

干杯的人。它工作完美。谢谢 – pythonnewbie

2

您可以检查是否字符是一个spacestr.isspace()加入ord(i)-96,如果它不是一个空间别的只是广告d炭:

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] 

在循环的等效代码如下:

a = [] 
for i in n: 
    if not i.isspace(): 
     a.append(ord(i)-96) 
    else: 
     a.append(i) 
+1

Doh!我3分钟太慢了! – LexyStardust

+1

感谢老板,帮了很大忙。 – pythonnewbie

1

你也可以做到这一点作为一个(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) 

使用string.whitespace list也意味着其他类型的空白将被保留,这可能对你有用?

+0

谢谢老板!欣赏它。 – pythonnewbie