如何将字符串分割为字符列表?Str.split不起作用。
"foobar" → ['f', 'o', 'o', 'b', 'a', 'r']
如何将字符串分割为字符列表?Str.split不起作用。
"foobar" → ['f', 'o', 'o', 'b', 'a', 'r']
当前回答
解压缩:
word = "Paralelepipedo"
print([*word])
其他回答
如果希望只读访问字符串,可以直接使用数组表示法。
Python 2.7.6 (default, Mar 22 2014, 22:59:38)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> t = 'my string'
>>> t[1]
'y'
对于不使用regexp的测试可能很有用。 字符串是否包含结束换行符?
>>> t[-1] == '\n'
False
>>> t = 'my string\n'
>>> t[-1] == '\n'
True
将字符串传递给list()
s = "mystring"
l = list(s)
print l
如果你想一次处理一个字符串字符。你有多种选择。
uhello = u'Hello\u0020World'
使用列表推导式:
print([x for x in uhello])
输出:
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
使用地图:
print(list(map(lambda c2: c2, uhello)))
输出:
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
调用内置列表函数:
print(list(uhello))
输出:
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
使用for循环:
for c in uhello:
print(c)
输出:
H
e
l
l
o
W
o
r
l
d
这个任务可以归结为遍历字符串中的字符并将它们收集到一个列表中。最naïve的解决方案是这样的
result = []
for character in string:
result.append(character)
当然,也可以缩写为just
result = [character for character in string]
但是仍然有更短的解来做同样的事情。
列表构造函数可用于将任何可迭代对象(迭代器、列表、元组、字符串等)转换为列表。
>>> list('abc')
['a', 'b', 'c']
最大的优点是它在Python 2和Python 3中工作方式相同。
此外,从Python 3.5开始(多亏了强大的PEP 448),现在可以通过将任何可迭代对象解包为空列表文本来构建列表:
>>> [*'abc']
['a', 'b', 'c']
这比直接调用列表构造函数更简洁,在某些情况下也更有效。
我建议不要使用基于map的方法,因为map在Python 3中不会返回一个列表。请参阅如何在Python 3中使用筛选、映射和还原。
您也可以在列表操作中使用extend方法。
>>> list1 = []
>>> list1.extend('somestring')
>>> list1
['s', 'o', 'm', 'e', 's', 't', 'r', 'i', 'n', 'g']