繁体   English   中英

如何将拆分字符串放入项目为字符的列表中?

[英]How can I put a split string into a list where the items are the chars?

例如,我想将字符串 num '123' 拆分为其字符(1、2 和 3)并将其放入列表 numlist 中。 但是,当我想要['1','2','3'] ] 时,使用num.split()它会给我['123'] ] 。 这可能吗?

num = "123"
numlist = list(num)

print(numlist)

输出:

['1', '2', '3']

如果您正在寻找一种通用方法,当您的num可能存储在变量中并且您需要将其添加到列表时,您可以使用以下方法:

num = 123
my_list = list(str(num))
my_list

输出:

['1', '2', '3']

简单的答案就是使用@Andrej Kesely 在评论中建议的list() ,如下所示:

s = '123'
res = list(s)
print(res) # ['1', '2', '3']

如果您需要操纵拆分发生的方式,您也可以使用列表推导:

s = '123'
res = [e for e in s]
print(res) # ['1', '2', '3']

为此你可以试试这个

a="123"
b=[]
for i in a:
    b.append(i)
print(b)

订阅有关 Python 的更多信息

数字 = '123'

字符串列表

a = 列表(编号); 打印(一)

整数列表

x = [int(num) for num in a]; 打印(x)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM