简体   繁体   English

在 Python 中将字符串转换为 integer 和反之亦然

[英]Converting string to integer and vice versa in Python

I have a string for example例如,我有一个字符串

>>> sample = "Hello World!"

What I want to make a function which can convert sample to int.我想做一个可以将sample转换为整数的 function。 I know about chr() and ord() .我知道chr()ord() I've used this so far:到目前为止我已经使用了这个:

For String to Int对于字符串到 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 .如何将res转换回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我找到了这个解决方案,但这很慢有人知道改进这个

I am saving the num seperated by " " so it is possible to go back through convert it easier我正在保存由“”分隔的数字,因此可以通过更轻松的转换将 go 恢复

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: output:

721011081081113287111114108100
Hello World
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?为了避免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.我们需要一个像数据结构这样的映射,而 dict 是存储每个字符串并使用enumerate将它们分配给唯一键的最佳方法,这将动态生成键。

Our d1 looks like this:我们的d1看起来像这样:

{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.然后是简单的部分,将字符串值转换为 int 并在其上应用chr以转换回字符串。

Since OP donot want to use multiple variables or data structures.由于OP不想使用多个变量或数据结构。

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问题是我们需要知道在哪里应用char所以我在每个字母上添加了一个额外的@以便很容易将它转换回来

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM