Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting string to integer in Python

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.

like image 578
shubhanshu-tomar Avatar asked Feb 24 '26 12:02

shubhanshu-tomar


2 Answers

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'

Update

Based on Copperfield's comment A better way to do following arithmetic operation

(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]
like image 192
RCvaram Avatar answered Feb 27 '26 02:02

RCvaram


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

like image 38
Aryan Avatar answered Feb 27 '26 01:02

Aryan