将字符串打印为 python 中的整数 3

Printing string as integers in python 3

我正在 python 3 中编写程序以将输入字符串转换为整数。代码只有一个问题。每当出现 space 时,它都会打印 -64。我试过编辑代码,但它会打印 -64 和 space。有什么建议吗?

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]

如果我理解正确的话,你想将 "abc def" 转换为 [1, 2, 3, " ", 4, 5, 6]。目前,您首先将 ord(i) - 96 添加到您的列表中,然后,如果该字符是 space,您将添加一个额外的 space。您只想添加 ord(i) - 96 如果它不是 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)

实际上你在检查条件 if (ord(i)-96) == -64 之前将 ord(i)-96 追加到 a,所以正确的方法是先检查条件,如果匹配则追加 " " else simple append 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)

您可以检查字符是否为 space 并添加 str.isspace() 如果它不是 space 则添加 ord(i)-96 否则只需添加字符:

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)

您也可以将其作为一个(大概)-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 列表还意味着将保留其他类型的空格,这可能对您有用?