Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:将列表中的字符串值更改为ascii值_Python_String_List_Append_Ascii - Fatal编程技术网

Python:将列表中的字符串值更改为ascii值

Python:将列表中的字符串值更改为ascii值,python,string,list,append,ascii,Python,String,List,Append,Ascii,我正在尝试将字符串中的字符转换为单个ascii值。我似乎无法将每个字符都转换为其相对ascii值 例如,如果变量字的值为[“hello”,“world”],则在运行完成的代码后,列表ascii的值为: [104、101、108、108、111、119、111、114、108、100] 到目前为止,我已经: words = ["hello", "world"] ascii = [] for x in words: ascii.append(ord(x)) 打印此命令会返回一个错误,因为o

我正在尝试将字符串中的字符转换为单个ascii值。我似乎无法将每个字符都转换为其相对ascii值

例如,如果变量字的值为[“hello”,“world”],则在运行完成的代码后,列表ascii的值为:

[104、101、108、108、111、119、111、114、108、100]

到目前为止,我已经:

words = ["hello", "world"]
ascii = []
for x in words:
    ascii.append(ord(x))

打印此命令会返回一个错误,因为ord需要一个字符,但得到一个字符串。有人知道我如何修复此问题以返回每个字母的ascii值吗?谢谢

将单词视为一个长字符串(例如使用嵌套列表comp):

相当于:

ascii = []
for word in words:
    for ch in word:
        ascii.append(ord(ch))
如果您想将它们作为单独的单词,则可以更改列表comp:

ascii = [[ord(ch) for ch in word] for word in words]
# [[104, 101, 108, 108, 111], [119, 111, 114, 108, 100]]

循环在
单词
列表上迭代,该列表是
字符串
的列表。现在,
ord
是一个函数,它将返回一个字符串的整数序号。因此,您还需要对字符串的字符进行迭代

words = ["hello", "world"]
ascii = []
for word in words:
    ascii.extend(ord(ch) for ch in word)
打印ascii
将为您提供

[104, 101, 108, 108, 111, 119, 111, 114, 108, 100]

如果我想将ascii变量打印为两个单独的列表呢?例如[104、101、108、108、111]、[119、111、114、108、100]]
[104, 101, 108, 108, 111, 119, 111, 114, 108, 100]