我有这个函数,它将一个名字作为输入,将它放入一个列表然后对它运行ord()。但是,我有一些(我相信)格式化问题。 我试图让它看起来像这样:
b = (ascii value)
a = (ascii value)
t = (ascii value)
m = (ascii value)
a = (ascii value)
n = (ascii value)
我的名字显示正确,但ascii值显示如下:
b = [98, 97, 116, 109, 97, 110]
a = [98, 97, 116, 109, 97, 110]
t = [98, 97, 116, 109, 97, 110]
m = [98, 97, 116, 109, 97, 110]
a = [98, 97, 116, 109, 97, 110]
n = [98, 97, 116, 109, 97, 110]
不知道我哪里出错了,下面是我为它做的代码:
def x():
name = requestString("name")
usersName = list(name)
ascii = [orc(c) for c in usersName]
for name in name:
print name, "=", ascii
谢谢!
编辑: 谢谢,非常感谢。到我错误的地方吧!
答案 0 :(得分:1)
ascii
是所有字符的ord
列表。要将它们与其代表的字符配对,请使用zip
:
for num, char in zip(ascii, name):
print "'{0}'={1}".format(char, num)
答案 1 :(得分:1)
这里有一些关于你出错的地方:
def x():
name = requestString("name")
usersName = list(name)
ascii = [orc(c) for c in usersName] # here's the list
for name in name:
print name, "=", ascii # and you're printing it here everytime
你可以像这样更加诡异地修复:
def x():
name = requestString("name")
# usersName = list(name) # no need for this line, you can iterate over the string
ascii = [orc(c) for c in name] #so this is just name
for i, c in enumerate(name): # use c for your character var name,
print c, "=", ascii[i] # and enumerate provides the index
由于您没有返回任何内容,因此无需创建列表,您也可以动态提供ord(c):
def print_ords_of_word(name):
for c in name:
print c, '=', ord(c)
答案 2 :(得分:1)
你可以在一个循环中完成它:
for item in name:
print item, "=", ord(item)
演示:
>>> def x(name):
... for item in name:
... print item, "=", ord(item)
...
>>> x('batman')
b = 98
a = 97
t = 116
m = 109
a = 97
n = 110
答案 3 :(得分:0)
[ord(c) for c in usersName]
是ord
中字母的所有usersName
值的列表。那不是你想要放在你的信件旁边的 - 你想把它当作一个。
你可以这样做:
def x():
name = requestString("name")
ascii = {letter:ord(letter) for letter in name}
for letter in name:
print(letter+" = "+ascii[letter])
# or use string formatting which is better
或者只是:
def x():
name = requestString("name")
for letter in name:
print(letter+" = "+ord(letter))
答案 4 :(得分:0)
您正在获取列表,因为您使用列表解析将整个usersName转换为ords列表。这可以用以下单行写成:
print "\n".join("{0} = {1}".format(c, ord(c)) for c in name)
字符串上的join方法接受一个序列或迭代器,并使用字符串的原始内容(在本例中为\ n)分隔每个项目。
加入调用中的for循环创建了一个生成器,你可以把它想象成一个列表理解,如果它可以帮助你更好地理解(但它确实不是)。