如何将字符串转换为 Python 中的列表 3
How to convert String to list in Python 3
用户输入后,变量colors = "58, 234, 209",为字符串。我需要将它转换为列表 - colors = [58, 234, 209]。哪种方式我可以做到。谢谢。
color = ("Enter color you like, something like that 58, 234, 209. ")
colors = input(color)
colors = colors.split()
这将拆分字符串中的每个空格
因为你有一些 non-space 个字符,比如 ,
,你需要使用灵活的拆分器,比如 re.split
:
import re
colors = input('Enter color you like, something like that 58, 234, 209. ')
colors = list(map(int, re.split(r'[^\d]+', colors)))
用户输入后,变量colors = "58, 234, 209",为字符串。我需要将它转换为列表 - colors = [58, 234, 209]。哪种方式我可以做到。谢谢。
color = ("Enter color you like, something like that 58, 234, 209. ")
colors = input(color)
colors = colors.split()
这将拆分字符串中的每个空格
因为你有一些 non-space 个字符,比如 ,
,你需要使用灵活的拆分器,比如 re.split
:
import re
colors = input('Enter color you like, something like that 58, 234, 209. ')
colors = list(map(int, re.split(r'[^\d]+', colors)))