Python For循环输出整数
此for循环应采用输入的输入,并将字符转换为整数Python For循环输出整数,python,for-loop,integer,Python,For Loop,Integer,此for循环应采用输入的输入,并将字符转换为整数 input = a output = [] for char in input: num = ord(char) - 96 output.append(num) 问题是,最后的输出等于“[1]” 我需要它是一个int来相乘。方法返回一个整数,表示给定Unicode字符的Unicode代码点 在您的情况下,您的输入是“a”,它由数字97表示 >>> print ord('a') 97 因此,当你从97中减去
input = a
output = []
for char in input:
num = ord(char) - 96
output.append(num)
问题是,最后的输出等于“[1]”
我需要它是一个int来相乘。方法返回一个整数,表示给定Unicode字符的Unicode代码点
在您的情况下,您的输入是“a”,它由数字97表示
>>> print ord('a')
97
因此,当你从97中减去96,你得到1
它已经是一个int
>>> if type(ord('a')) is int:
... print 'is int'
... else:
... pass
...
is int
最后,如果要将其相乘,请将运算符从“-”更改为“*”
>>> input = 'B'
>>> print ord(input)
66
>>> output = []
>>> for char in input:
... num = ord(char) * 2
... print num
132
我的答案假设输入是一个数字,但是是字符串格式的,并且您希望对其进行迭代。因为如果是一个小数字,您可以:
int(input)
我需要更多的解释来澄清我的答案。希望这能有所帮助。那么为什么要将其附加到列表中?为什么要以
输出
列表开头?第一行应该是input=“a”
?顺便说一句,您不应该使用input
作为变量名,因为这会影响内置的input
函数。要使用它的索引n=output[0]
。您的输入是一个只包含数字的字符串吗?我想OP希望对ord(char)-96
的结果进行算术运算。
input = a
output = []
total = 0;
for char in input:
num = int(char)
total = (total*10)+num
int(input)