30
A
回答
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'
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
相關問題
- 1. 將字符串轉換爲ASCII值
- 2. C++ ::將ASCII值轉換爲字符串
- 3. 將字符串轉換爲ASCII值
- 4. 將字符串轉換爲字符ascii
- 5. 將字符串轉換爲ascii和ascii爲字符串
- 6. Python:將ascii字符串轉換爲unicode字符串
- 7. Python將ASCII字符轉換爲字節
- 8. 將字符串轉換爲ASCII和ASCII字符串
- 9. 如何將ascii值列表轉換爲python中的字符串?
- 10. 如何將ASCII字符轉換爲Python中的字符串
- 11. python將未知字符轉換爲ascii
- 12. 將Ascii字符串轉換爲位流
- 13. 將字符串轉換爲ASCII
- 14. 將字符串轉換爲ASCII碼
- 15. 將字符串轉換爲ASCII碼
- 16. 將Unicode字符串轉換爲ASCII
- 17. 將數值轉換爲ASCII字符?
- 18. 將ASCII碼轉換爲字符值
- 19. 將ascii值轉換爲字符
- 20. Bash:將非ASCII字符轉換爲ASCII
- 21. C++將字符串字母轉換爲整型值(ASCII)
- 22. 將ASCII字符轉換爲十六進制轉義字符串
- 23. 如何將utf8字符串轉換爲ascii字符串?
- 24. Java:如何將ASCII字符串轉換爲字符串?
- 25. 將字符轉換爲ASCII字符
- 26. Python將混合ASCII碼轉換爲字符串
- 27. 將Unicode字符串轉換爲Python中的ASCII 2.7
- 28. 將Python字符串轉換爲其ASCII碼錶示形式
- 29. Python 2.7,將utf8字符串轉換爲ascii
- 30. 如何將一串ascii值轉換爲Python中的原始字符/數字
我在想什麼?這比我的pythonic多得多。這就是我在閱讀了一堆Haskell問題之後試圖回答python問題所得到的結果。+1 – Nate