python:将字符串解压缩到列表 [英] python: unpacking a string to a list
问题描述
关于配置文件中多值元素的问题的答案(这完全适合我需求)建议从配置中解压缩字符串".我阅读了解压缩参数列表的文档但是我不明白这与我的问题有什么关系.
The answer to a question on multiple-value elements in a config file (which exactly fits my needs) suggests to "unpack the string from the config". I read the doc for unpacking arguments lists suggested in several places but I fail to understand how this relates to my problem.
我确信这很明显:拥有一个字符串str = "123,456"
,如何将其转换为列表[123,456]
(字符串中用逗号分隔的元素数量可能会有所不同)
I am sure this must be obvious: having a string str = "123,456"
, how can I transform it into the list [123,456]
(the number of elements separated by a comma in the string may vary)
谢谢.
推荐答案
您要使用字符串列表还是整数列表?
Do you want a list of strings or a list of ints?
如果只需要一个字符串列表,这很简单:
If you just want a list of strings, it's very simple:
my_list = my_string.split(',')
如果要将这些转换为整数,则需要:
If you want to convert these to ints, you need:
my_list = map(int, my_string.split(','))
(此外,不要使用str
作为变量名,因为它会遮盖内置的str()
函数.)
(Also, don't use str
as a variable name as it shadows the built-in str()
function.)
这篇关于python:将字符串解压缩到列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!