Is there a method that converts a string of text such as 'you'
to a number other than
y = tuple('you')
for k in y:
k = ord(k)
which only converts one character at a time?
In order to convert a string to a number (and the reverse), you should first always work with bytes
. Since you are using Python 3, strings are actually Unicode strings and as such may contain characters that have a ord()
value higher than 255. bytes
however just have a single byte per character; so you should always convert between those two types first.
So basically, you are looking for a way to convert a bytes
string (which is basically a list of bytes, a list of numbers 0–255) into a single number, and the inverse. You can use int.to_bytes
and int.from_bytes
for that:
import math
def convertToNumber (s):
return int.from_bytes(s.encode(), 'little')
def convertFromNumber (n):
return n.to_bytes(math.ceil(n.bit_length() / 8), 'little').decode()
>>> convertToNumber('foo bar baz')
147948829660780569073512294
>>> x = _
>>> convertFromNumber(x)
'foo bar baz'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With