繁体   English   中英

将字符串转换为 Python 中的 integer

[英]converting string to integer in Python

我试图在 python 中将字符串列表转换为 integer 如下:

plain = input("string >> ")
string_list = list(plain)
print(string_list)
ASCII = []

for x in range (0, len(string_list)):
    ASCII.append([ord(string_list[x])])

print(ASCII)

for x in range (0, len(ASCII)):
    print(ASCII[x])
    integer_ASCII = type(int(ASCII[x]))
    print(integer_ASCII, end=", ")

但我收到此错误:

TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

那么有没有其他方法可以将字符串转换为 integer。

这是否解决了您的错误?

string_list = list("test")
print(string_list)
ASCII = []

for x in range(0, len(string_list)):
    ASCII.append([ord(string_list[x])])

print(ASCII)

integer_ASCII = []
str_integer_ASCII = []

for x in range(0, len(ASCII)):
    integer_ASCII.append(int(ASCII[x][0]))
    str_integer_ASCII.append(str(ASCII[x][0]))

print("\n")
print("INT LIST VERSION:", integer_ASCII, type(integer_ASCII))
print("STRING LIST VERSION:", str_integer_ASCII, type(str_integer_ASCII))
print("FULL STRING VERSION: ", ' '.join(str_integer_ASCII), type(' '.join(str_integer_ASCII)))

希望这些信息对您有用!
快乐编码

而不是 ascii 值,您将列表附加到 ASCII 首先,我们将 map 每个字符串字符转换为 ASCII 值并将其转换为字符串类型。 然后加入加入function。

e = 100
n = 20
text = input("string >>>")
#This will return int ascii values for each character. Here you can do any arithmatic operations
rsa_values = list(map(lambda x:(ord(x)**e) % n , text))#[16, 1, 5, 16]


#TO get the same you can list compression also
rsa_values = [ (ord(x)**e) % n for x in text] #[16, 1, 5, 16]



#if you need to join them as string then use join function.
string_ascii_values = "".join(chr(i) for i in ascii_values)#'\x10\x01\x05\x10'

更新

基于科波菲尔的评论更好的方法来做以下算术运算

(ord(x)**e) % n

pow(ord(x), e, n)

 rsa_values = [ pow(ord(x), e, n) for x in text] #[16, 1, 5, 16]

只需使用将列表中的每个字符串转换为 int 的列表推导:

list_of_ints = [int(x) for x in string_list]

或者,如果您想要字符串中每个 char 的 char 值(这是您从input()获得的 - 无需调用list() ):

list_of_char_values = [ord(x) for x in string]

简单来说也是可能的。 请查找有关理解 python的信息。

>>> [ord(x) for x in 'abcde']
[97, 98, 99, 100, 101]

这似乎对我有用,您在每个号码的列表中都有一个列表。

plain = 'test'
string_list = list(plain)
print(string_list)
ASCII = []

for x in range (0, len(string_list)):
    ASCII.append([ord(string_list[x])])

print(ASCII)

for x in range (0, len(ASCII)):
    print(ASCII[x])
    integer_ASCII = type(int(ASCII[x][0]))
    print(integer_ASCII, end=", ")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM