我该如何将一个字符串拆分成字符列表?str.split
不能用。
"foobar" → ['f', 'o', 'o', 'b', 'a', 'r']
cast_method = lambda x:[x]
来避免这种行为。 - madzohans = "mystring"
l = list(s)
print l
您也可以用非list()的方式来非常简单地完成它:
>>> [c for c in "foobar"]
['f', 'o', 'o', 'b', 'a', 'r']
list(map(lambda c: c, iter("foobar")))
,但更易读且更有意义。 - InQβuhello = u'Hello\u0020World'
使用列表推导式:
print([x for x in uhello])
输出:
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
使用map:
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
如果你只需要一个字符数组:
arr = list(str)
如果你想按特定的分隔符拆分字符串:# str = "temp//temps" will will be ['temp', 'temps']
arr = str.split("//")
我探索了另外两种方法来完成这个任务。对于某些人可能会有所帮助。
第一种方法很简单:
In [25]: a = []
In [26]: s = 'foobar'
In [27]: a += s
In [28]: a
Out[28]: ['f', 'o', 'o', 'b', 'a', 'r']
第二种方法使用 map
和 lambda
函数。这种方法适用于更复杂的任务:
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文档获取更多方法。
result = []
for character in string:
result.append(character)
当然,它可以简化为:result = [character for character in string]
但仍然有更短的解决方案可以完成相同的事情。
list
构造函数可用于将任何 可迭代对象(迭代器、列表、元组、字符串等)转换为列表。
>>> list('abc')
['a', 'b', 'c']
最大的优点是它在Python 2和Python 3中使用方式相同。
另外,从Python 3.5开始(感谢神奇的PEP 448),现在可以通过将可迭代对象拆包到空列表字面量中来构建列表:
>>> [*'abc']
['a', 'b', 'c']
这比直接调用 list
构造函数更加整洁,并且在某些情况下更有效率。
我建议不要使用基于 map
的方法,因为在 Python 3 中,map
不会返回列表。请参见 如何在Python 3中使用filter、map和reduce。
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']
将它们解压:
word = "Paralelepipedo"
print([*word])
将字符串 s
分割的最简单方法是将其传递给 list()
。因此,
s = 'abc'
s_l = list(s) # s_l is now ['a', 'b', 'c']
你也可以使用列表推导式,虽然它的效果与上面的代码相同,但不如上面的代码简洁:
s_l = [c for c in s]
还有其他方法,但这些应该足够了。如果以后想要重新组合它们,使用简单的调用"".join(s_l)
将把列表作为字符串返回...