如何将字符串转换为ASCII值?
例如,"hi"将返回[104 105]。
我可以分别使用ord('h')和ord('i'),但是当有很多字母时,这将变得麻烦。
例如,"hi"将返回[104 105]。
我可以分别使用ord('h')和ord('i'),但是当有很多字母时,这将变得麻烦。
你可以使用列表推导式:
>>> s = 'hi'
>>> [ord(c) for c in s]
[104, 105]
这里有一种相当简洁的方法来执行字符串拼接:
>>> s = "hello world"
>>> ''.join(str(ord(c)) for c in s)
'10410110810811132119111114108100'
还有一种有趣的替代方法:
>>> '%d'*len(s) % tuple(map(ord, s))
'10410110810811132119111114108100'
在2021年,我们可以假设只有Python 3是相关的,所以...
如果您的输入是bytes
:
>>> list(b"Hello")
[72, 101, 108, 108, 111]
如果你的输入是str
:
>>> list("Hello".encode('ascii'))
[72, 101, 108, 108, 111]
如果您希望一个适用于两种情况的解决方案:
list(bytes(text, 'ascii'))
(如果str
包含非ASCII字符,以上所有内容都会有意地引发UnicodeEncodeError
。这是一个合理的假设,因为询问非ASCII字符的“ASCII值”是没有意义的。)
>>> list(bytes(b'test'))
[116, 101, 115, 116]
bytes()
是多余的,而对于字符串输入,你需要指定一个编码。 - MestreLion>>> reduce(lambda x, y: str(x)+str(y), map(ord,"hello world"))
'10410110810811132119111114108100'
您的描述有些混淆不清,在大多数情况下,直接连接十进制值似乎并没有什么用处。以下代码将把每个字母转换为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
很难理解为什么要连接(十进制)“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']
>>> ["".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']
>>>
def stringToNumbers(ord(message)):
return stringToNumbers
stringToNumbers.append = (ord[0])
stringToNumbers = ("morocco")
import numpy as np
a = np.fromstring('hi', dtype=np.uint8)
print(a)
fromstring
现已弃用,因此最好使用类似于np.frombuffer(b'hi', dtype=np.uint8)
的方法。 - Alex Moore-Niemiimport numpy as np
text = "hi"
np.array([text]).view('int32').tolist() # [104, 105]
ord()
函数类似,上述操作返回字符的Unicode代码点(如果字符串很长,则速度更快),而.encode()
将字符串文字编码为字节文字,只允许ASCII字符。对于当前问题的范围来说,这不是一个问题,但如果你有一个非ASCII字符,比如日语、俄语等,你可能得不到你期望的结果。s = "Меси"
list(map(ord, s)) # [1052, 1077, 1089, 1080]
np.array([s]).view('int32').tolist() # [1052, 1077, 1089, 1080]
list(s.encode()) # [208, 156, 208, 181, 209, 129, 208, 184]
np.array([text]).view(dtype=np.int32).tolist()
和np.array([s]).view(dtype=int32).tolist()
。 - undefined