【问题标题】:How can I convert string to get ASCII numbers in python? [duplicate]如何在 python 中转换字符串以获取 ASCII 数字? [复制]
【发布时间】:2018-10-28 15:18:51
【问题描述】:

我有这个代码:

str = "text"
x = str.encode('ascii')
print(x)

我得到了这个: b'文本'

我想得到这个: “116 101 120 116”作为字符串。 我想要像here 这样的解决方案。

【问题讨论】:

  • print(list(x)) 为您提供整数。 print(*x) 会给你以空格分隔的整数。
  • 请不要重新定义“str”等内置函数。它可能会破坏更复杂的代码。示例:isinstance('anything', str) 将无法按预期工作。

标签: python ascii encode


【解决方案1】:
print ([ord(c) for c in 'text'])
# [116, 101, 120, 116]

来自docs

给定一个长度为 1 的字符串,当参数是 unicode 对象时,返回一个整数,表示字符的 Unicode 代码点,或者当参数是 8 位字符串时,返回字节的值。例如,ord('a') 返回整数 97,ord(u'\u2020') 返回 8224。这是 chr() 用于 8 位字符串和 unichr() 用于 unicode 对象的倒数。如果给出了 unicode 参数并且 Python 是使用 UCS2 Unicode 构建的,那么字符的代码点必须在 [0..65535] 范围内;否则字符串长度为 2,会引发 TypeError。

【讨论】:

    【解决方案2】:

    使用 map 将每个字符映射到它的 ascii 值

    str1 = "text"
    list(map(ord,str1))
    

    如果需要作为字符串输出

    str1 = "text"
    ' '.join(list(map(str,map(ord,str1))))
    

    【讨论】:

    • 似乎这比下面的方法快了几乎 2 的倍数。
    猜你喜欢
    • 2012-07-20
    • 2020-04-20
    • 1970-01-01
    • 1970-01-01
    • 2017-02-12
    • 2021-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多