我有长字符串,我想把它作为一个长号。 我想:Python字符串作为长号
l=[ord (i)for i in str1]
但这不是我所需要的。 我需要使它长数字而不是数字作为列表中的项目。 这一行给我[23,21,45,34,242,32]
,我想让它变成一个很长的数字,我可以再次将其更改为相同的字符串。
有什么想法吗?
我有长字符串,我想把它作为一个长号。 我想:Python字符串作为长号
l=[ord (i)for i in str1]
但这不是我所需要的。 我需要使它长数字而不是数字作为列表中的项目。 这一行给我[23,21,45,34,242,32]
,我想让它变成一个很长的数字,我可以再次将其更改为相同的字符串。
有什么想法吗?
这是我发现的作品的代码。
str='sdfsdfsdfdsfsdfcxvvdfvxcvsdcsdcs sdcsdcasd'
I=int.from_bytes(bytes([ord (i)for i in str]),byteorder='big')
print(I)
print(I.to_bytes(len(str),byteorder='big'))
如何使用base 64
编码?你很好吗?这里有一个例子:
>>>import base64
>>>s = 'abcde'
>>>e = base64.b64encode(s)
>>>print e
YWJjZGU=
>>>base64.b64decode(e)
'abcde'
的编码不是纯数字但你可以去从字符串来回没有太多的麻烦。
您也可以尝试将字符串编码为十六进制。这将产生号码,不过我不知道,你可以随时来从编码字符串返回到原始字符串:
>>>s='abc'
>>>n=s.encode('hex')
>>>print n
'616263'
>>>n.decode('hex')
'abc'
如果你需要它是实际整数那么你可以扩展的伎俩:
>>>s='abc'
>>>n=int(s.encode('hex'), 16) #convert it to integer
>>>print n
6382179
hex(n)[2:].decode('hex') # return from integer to string
>>>abc
注:我不知道这项工作的开箱即用Python 3
UPDATE:,使其与Python的工作3我建议使用binascii
module是这样的:需要
>>>import binascii
>>>s = 'abcd'
>>>n = int(binascii.hexlify(s.encode()), 16) # encode is needed to convert unicode to bytes
>>>print(n)
1633837924 #integer
>>>binascii.unhexlify(hex(n)[2:].encode()).decode()
'abcd'
encode
和decode
方法从字节串并转换相反。如果您打算包含特殊(非ASCII)字符,那么您可能需要指定编码。
希望这会有所帮助!
这是你在找什么:
>>> str = 'abcdef'
>>> ''.join([chr(y) for y in [ ord(x) for x in str ]])
'abcdef'
>>>
#! /usr/bin/python2
# coding: utf-8
def encode(s):
result = 0
for ch in s.encode('utf-8'):
result *= 256
result += ord(ch)
return result
def decode(i):
result = []
while i:
result.append(chr(i%256))
i /= 256
result = reversed(result)
result = ''.join(result)
result = result.decode('utf-8')
return result
orig = u'Once in Persia reigned a king …'
cipher = encode(orig)
clear = decode(cipher)
print '%s -> %s -> %s'%(orig, cipher, clear)
这里是圣保罗卜的回答翻译(用base64编码)成Python 3:
>>> import base64
>>> s = 'abcde'
>>> e = base64.b64encode(s.encode('utf-8'))
>>> print(e)
b'YWJjZGU='
>>> base64.b64decode(e).decode('utf-8')
'abcde'
基本上差别您的工作流程已从:
string -> base64
base64 -> string
收件人:
string -> bytes
bytes -> base64
base64 -> bytes
bytes -> string
你能粘贴你的字符串吗? –
str1 =?你需要那个字符串 –
str1这是一个字符串。想想str1 ='askdjh' – Alon