Python 字符串转列表

Python 字符串与列表之间相互转换

1. 字符串转列表

test_str = "Hello World"
test_list = test_str.split(" ")

输出:
['Hello', 'World']

2. 列表转字符串

test_list = ["Hello", "World"]
test_str = " ".join(test_list)

输出:
"Hello World"

3.字符串形式列表转出列表

3.1 利用Python内置函数eval()进行处理

test_str = '["Hello", "World"]'
test_list = eval(test_str)

输出:
["Hello", "World"]

3.2 利用literal_eval进行转换

from ast import literal_eval

test_str = '["Hello", "World"]'
test_list = literal_eval(test_str)

输出:
["Hello", "World"]
posted @ 2021-11-29 14:48  KB、渣科  阅读(899)  评论(0编辑  收藏  举报