如何将字符串转换为 python 中的 ASCII 数字?
How can I convert string to get ASCII numbers in python?
我有这个代码:
str = "text"
x = str.encode('ascii')
print(x)
我明白了:
b'文本'
我想得到这个:
“116 101 120 116”作为字符串。
我想要像 here 这样的解决方案。
print ([ord(c) for c in 'text'])
# [116, 101, 120, 116]
来自docs:
Given a string of length one, return an integer representing the Unicode code point of the character when the argument is a unicode object, or the value of the byte when the argument is an 8-bit string. For example, ord('a') returns the integer 97, ord(u'\u2020') returns 8224. This is the inverse of chr() for 8-bit strings and of unichr() for unicode objects. If a unicode argument is given and Python was built with UCS2 Unicode, then the character’s code point must be in the range [0..65535] inclusive; otherwise the string length is two, and a TypeError will be raised.
使用 map 将每个字符映射到它的 ascii 值
str1 = "text"
list(map(ord,str1))
如果需要作为字符串输出
str1 = "text"
' '.join(list(map(str,map(ord,str1))))
我有这个代码:
str = "text"
x = str.encode('ascii')
print(x)
我明白了: b'文本'
我想得到这个: “116 101 120 116”作为字符串。 我想要像 here 这样的解决方案。
print ([ord(c) for c in 'text'])
# [116, 101, 120, 116]
来自docs:
Given a string of length one, return an integer representing the Unicode code point of the character when the argument is a unicode object, or the value of the byte when the argument is an 8-bit string. For example, ord('a') returns the integer 97, ord(u'\u2020') returns 8224. This is the inverse of chr() for 8-bit strings and of unichr() for unicode objects. If a unicode argument is given and Python was built with UCS2 Unicode, then the character’s code point must be in the range [0..65535] inclusive; otherwise the string length is two, and a TypeError will be raised.
使用 map 将每个字符映射到它的 ascii 值
str1 = "text"
list(map(ord,str1))
如果需要作为字符串输出
str1 = "text"
' '.join(list(map(str,map(ord,str1))))