将字符串转换为ASCII值python

Nea*_*ang 55 python ascii

如何将字符串转换为ASCII值?

例如,"hi"将返回104105.

我可以单独做ord('h')和ord('i'),但是当有很多字母时它会很麻烦.

Mar*_*ers 96

您可以使用列表理解:

>>> s = 'hi'
>>> [ord(c) for c in s]
[104, 105]
Run Code Online (Sandbox Code Playgroud)


And*_*ark 22

这是执行连接的一种非常简洁的方法:

>>> s = "hello world"
>>> ''.join(str(ord(c)) for c in s)
'10410110810811132119111114108100'
Run Code Online (Sandbox Code Playgroud)

还有一种有趣的选择:

>>> '%d'*len(s) % tuple(map(ord, s))
'10410110810811132119111114108100'
Run Code Online (Sandbox Code Playgroud)

  • 我在想什么 这比我的多得多。这就是我在阅读一堆Haskell问题之后尝试回答python问题的结果... +1 (2认同)

Mes*_*ion 15

到 2021 年,我们可以假设只有 Python 3 是相关的,所以……

如果您的输入是bytes

>>> list(b"Hello")
[72, 101, 108, 108, 111]
Run Code Online (Sandbox Code Playgroud)

如果您的输入是str

>>> list("Hello".encode('ascii'))
[72, 101, 108, 108, 111]
Run Code Online (Sandbox Code Playgroud)

如果您想要一个同时适用于两者的解决方案:

list(bytes(text, 'ascii'))
Run Code Online (Sandbox Code Playgroud)

UnicodeEncodeError(如果包含非 ASCII 字符,以上所有内容都会有意引发str。这是一个公平的假设,因为询问非 ASCII 字符的“ASCII 值”是没有意义的。)


dev*_*unt 7

如果您使用的是 python 3 或更高版本,

>>> list(bytes(b'test'))
[116, 101, 115, 116]
Run Code Online (Sandbox Code Playgroud)


Nat*_*ate 6

如果您想要将结果连接起来,正如您在问题中所示,您可以尝试以下方法:

>>> reduce(lambda x, y: str(x)+str(y), map(ord,"hello world"))
'10410110810811132119111114108100'
Run Code Online (Sandbox Code Playgroud)