2014-01-20 43 views
2

我有长字符串,我想把它作为一个长号。 我想:Python字符串作为长号

l=[ord (i)for i in str1] 

但这不是我所需要的。 我需要使它长数字而不是数字作为列表中的项目。 这一行给我[23,21,45,34,242,32] ,我想让它变成一个很长的数字,我可以再次将其更改为相同的字符串。

有什么想法吗?

+0

你能粘贴你的字符串吗? –

+0

str1 =?你需要那个字符串 –

+0

str1这是一个字符串。想想str1 ='askdjh' – Alon

回答

0

这是我发现的作品的代码。

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')) 
0

如何使用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' 

encodedecode方法从字节串并转换相反。如果您打算包含特殊(非ASCII)字符,那么您可能需要指定编码。

希望这会有所帮助!

+0

我需要numbers.I这将其更改为二进制和每3个1,0,0 premutation我从1到9的数字 – Alon

+0

python中的任何功能,这样做?或类似的东西? – Alon

+0

@ user3160197看看我用'hexadecimals'编辑 –

0

这是你在找什么:

>>> str = 'abcdef' 
>>> ''.join([chr(y) for y in [ ord(x) for x in str ]]) 
'abcdef' 
>>> 
0
#! /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) 
1

这里是圣保罗卜的回答翻译(用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