简体   繁体   English

将字符串转换为 ASCII 值 python

[英]Convert string to ASCII value python

How would you convert a string to ASCII values?您如何将字符串转换为 ASCII 值?

For example, "hi" would return [104 105] .例如,“hi”将返回[104 105]

I can individually do ord('h') and ord('i'), but it's going to be troublesome when there are a lot of letters.我可以单独做ord('h')和ord('i'),但是当字母很多时会很麻烦。

You can use a list comprehension:您可以使用列表理解:

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

Here is a pretty concise way to perform the concatenation:这是执行串联的一种非常简洁的方法:

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

And a sort of fun alternative:还有一种有趣的选择:

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

If you are using python 3 or above,如果您使用的是 python 3 或更高版本,

>>> list(bytes(b'test'))
[116, 101, 115, 116]

If you want your result concatenated, as you show in your question, you could try something like:如果您希望将结果连接起来,如您在问题中所示,您可以尝试以下操作:

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

In 2021 we can assume only Python 3 is relevant, so...在 2021 年,我们可以假设只有 Python 3 是相关的,所以......

If your input is bytes :如果您的输入是bytes

>>> list(b"Hello")
[72, 101, 108, 108, 111]

If your input is str :如果您的输入是str

>>> list("Hello".encode('ascii'))
[72, 101, 108, 108, 111]

If you want a single solution that works with both:如果您想要一个同时适用于两者的解决方案:

list(bytes(text, 'ascii'))

(all the above will intentionally raise UnicodeEncodeError if str contains non-ASCII chars. A fair assumption as it makes no sense to ask for the "ASCII value" of non-ASCII chars.) (如果str包含非 ASCII 字符,则上述所有内容都会有意引发UnicodeEncodeError 。一个公平的假设,因为要求非 ASCII 字符的“ASCII 值”是没有意义的。)

your description is rather confusing;你的描述相当混乱; directly concatenating the decimal values doesn't seem useful in most contexts.在大多数情况下,直接连接十进制值似乎没有用。 the following code will cast each letter to an 8-bit character, and THEN concatenate.以下代码将每个字母转换为 8 位字符,然后连接。 this is how standard ASCII encoding works这就是标准 ASCII 编码的工作原理

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

you can actually do it with numpy:你实际上可以用 numpy 做到这一点:

import numpy as np
a = np.fromstring('hi', dtype=np.uint8)
print(a)

It is not at all obvious why one would want to concatenate the (decimal) "ascii values".为什么要连接(十进制)“ascii 值”,这一点并不明显。 What is certain is that concatenating them without leading zeroes (or some other padding or a delimiter) is useless -- nothing can be reliably recovered from such an output.可以肯定的是,在没有前导零(或其他一些填充或分隔符)的情况下连接它们是没有用的——从这样的输出中无法可靠地恢复任何东西。

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

Note that the first 3 outputs are of different length.请注意,前 3 个输出的长度不同。 Note that the fourth result is the same as the first.请注意,第四个结果与第一个结果相同。

>>> ["".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']
>>>

Note no such problems.注意没有这样的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM