Reputation: 55
I was trying to convert a string list to integer in python as follows:
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=", ")
but I get this error:
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'
So is there any other way to convert a string to integer.
Upvotes: 3
Views: 674
Reputation: 6333
instead of ascii value, your are appending a list to ASCII First, we map each string character to ASCII value and convert it into a string type. Then join with the join 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
is
pow(ord(x), e, n)
rsa_values = [ pow(ord(x), e, n) for x in text] #[16, 1, 5, 16]
Upvotes: 2
Reputation: 438
Simply it is possible also. Please find about comprehension python.
>>> [ord(x) for x in 'abcde']
[97, 98, 99, 100, 101]
Upvotes: 1
Reputation: 1113
Does this resolve your error?
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)))
Hope so this information is useful to you!
Happy Coding
Upvotes: 2
Reputation: 675
Just use a list comprehension that converts each string in the list into an int:
list_of_ints = [int(x) for x in string_list]
Or if you want the char value of each char in the string (which is what you get from input()
-- no need to call list()
on it):
list_of_char_values = [ord(x) for x in string]
Upvotes: 1
Reputation: 63
this seemed to work for me, you have a list inside of a list for each number.
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=", ")
Upvotes: -1