如何将字符串分割为字符列表?Str.split不起作用。
"foobar" → ['f', 'o', 'o', 'b', 'a', 'r']
如何将字符串分割为字符列表?Str.split不起作用。
"foobar" → ['f', 'o', 'o', 'b', 'a', 'r']
当前回答
from itertools import chain
string = 'your string'
chain(string)
类似于list(string),但返回的生成器在使用点被延迟计算,因此内存效率高。
其他回答
Split()内置函数只会在特定条件的基础上分离值,但在单个词中,它不能满足条件。因此,可以借助list()来解决。它在内部调用数组,并根据数组存储值。
假设,
a = "bottle"
a.split() // will only return the word but not split the every single char.
a = "bottle"
list(a) // will separate ['b','o','t','t','l','e']
将字符串传递给list()
s = "mystring"
l = list(s)
print l
使用列表构造函数:
>>> list("foobar")
['f', 'o', 'o', 'b', 'a', 'r']
List使用通过迭代输入iterable获得的项构建一个新列表。字符串是一个可迭代对象——在每个迭代步骤中迭代它会产生一个单独的字符。
如果希望只读访问字符串,可以直接使用数组表示法。
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
我探索了另外两种方法来完成这项任务。它可能对某人有帮助。
第一个很简单:
In [25]: a = []
In [26]: s = 'foobar'
In [27]: a += s
In [28]: a
Out[28]: ['f', 'o', 'o', 'b', 'a', 'r']
第二个使用map和函数。它可能适用于更复杂的任务:
In [36]: s = 'foobar12'
In [37]: a = map(lambda c: c, s)
In [38]: a
Out[38]: ['f', 'o', 'o', 'b', 'a', 'r', '1', '2']
例如
# isdigit, isspace or another facilities such as regexp may be used
In [40]: a = map(lambda c: c if c.isalpha() else '', s)
In [41]: a
Out[41]: ['f', 'o', 'o', 'b', 'a', 'r', '', '']
有关更多方法,请参阅python文档