2011-12-09 132 views

回答

55

您可以使用列表理解:

>>> s = 'hi' 
>>> [ord(c) for c in s] 
[104, 105] 
5

如果你想你的結果串接,爲你展示你的問題,你可以嘗試像:

>>> reduce(lambda x, y: str(x)+str(y), map(ord,"hello world")) 
'10410110810811132119111114108100' 
12

這是一個非常簡潔方式來執行級聯:

>>> s = "hello world" 
>>> ''.join(str(ord(c)) for c in s) 
'10410110810811132119111114108100' 

還有一種有趣的選擇:

>>> '%d'*len(s) % tuple(map(ord, s)) 
'10410110810811132119111114108100' 
+0

我在想什麼?這比我的pythonic多得多。這就是我在閱讀了一堆Haskell問題之後試圖回答python問題所得到的結果。+1 – Nate

1

這並不明顯,爲什麼要連接(十進制)「ascii值」。可以肯定的是,將它們連接起來而不用前導零(或其他填充或分隔符)是無用的 - 沒有任何東西可以可靠地從這樣的輸出中恢復。

>>> tests = ["hi", "Hi", "HI", '\x0A\x29\x00\x05'] 
>>> ["".join("%d" % ord(c) for c in s) for s in tests] 
['104105', '72105', '7273', '104105'] 

請注意,前3個輸出的長度不同。請注意,第四個結果與第一個結果相同。

>>> ["".join("%03d" % ord(c) for c in s) for s in tests] 
['104105', '072105', '072073', '010041000005'] 
>>> [" ".join("%d" % ord(c) for c in s) for s in tests] 
['104 105', '72 105', '72 73', '10 41 0 5'] 
>>> ["".join("%02x" % ord(c) for c in s) for s in tests] 
['6869', '4869', '4849', '0a290005'] 
>>> 

請注意沒有這樣的問題。

2
def stringToNumbers(ord(message)): 
    return stringToNumbers 
    stringToNumbers.append = (ord[0]) 
    stringToNumbers = ("morocco") 
1

你的描述比較混亂;直接連接十進制值在大多數情況下似乎並不有用。以下代碼將把每個字母轉換爲8位字符,然後連接。這是標準ASCII編碼如何工作

def ASCII(s): 
    x = 0 
    for i in xrange(len(s)): 
     x += ord(s[i])*2**(8 * (len(s) - i - 1)) 
    return x