[英]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.