Reputation: 764
I have a string for example
>>> sample = "Hello World!"
What I want to make a function which can convert sample
to int. I know about chr()
and ord()
. I've used this so far:
For String to Int
>>> res="".join([str(ord(char)) for char in sample])
>>> print(res)
72101108108111328711111410810033
Now the problem arise. How can I convert res
back to sample
. Any suggestion would be appreciated.
Note: sample string can also have unicode characters in it
Edit :
nchars=len(sample)
res = sum(ord(sample[byte])<<8*(nchars-byte-1) for byte in range(nchars)) # string to int
print(''.join(chr((res>>8*(nchars-byte-1))&0xFF) for byte in range(nchars))) #int to string
I found this solution but this is very slow do someone know to improve this
Upvotes: 1
Views: 1067
Reputation: 5347
sample = "Hello World!"
d1={k:str(ord(v)) for k,v in list(enumerate(sample))}
''.join(d1.values())
'72101108108111328711111410810033'
res1="".join([chr(int(char)) for char in d1.values()])
res1
'Hello World!'
In order to avoid the problem of which ord(chr) belongs to which chr?
we need a mapping like data structure and dict is the best to store the each string and assign them to unique key using enumerate
which will generate the keys on fly.
Our d1
looks like this:
{0: '72',
1: '101',
2: '108',
3: '108',
4: '111',
5: '32',
6: '87',
7: '111',
8: '114',
9: '108',
10: '100',
11: '33'}
then comes the easy part converting the string values to int and applying chr
on it to convert back into string.
Since OP
donot want to use multiple variables or data structures.
sample = "Hello World!"
l_n=[str(ord(i))+str(ord('@')) for i in list(sample)]
text="".join(l_n)
n_l=[chr(int(i)) for i in text.split('64') if i.isnumeric()]
''.join(n_l)
The problem is we need to know where to apply char
so I've added an extra @
to each letter so that it would be easy to convert it back
Upvotes: 0
Reputation: 396
I am saving the num seperated by " " so it is possible to go back through convert it easier
This works and is simple:
i = "Hello World"
num = ""
for char in i:
num += str(ord(char))+" "
print(''.join(num.split()))
back = ""
for n in num.split():
back += chr(int(n))
print(back)
output:
721011081081113287111114108100
Hello World
Upvotes: 1