如何将字符串分割为字符列表?Str.split不起作用。

"foobar"    →    ['f', 'o', 'o', 'b', 'a', 'r']

当前回答

解压缩:

word = "Paralelepipedo"
print([*word])

其他回答

您也可以在列表操作中使用extend方法。

>>> list1 = []
>>> list1.extend('somestring')
>>> list1
['s', 'o', 'm', 'e', 's', 't', 'r', 'i', 'n', 'g']

解压缩:

word = "Paralelepipedo"
print([*word])

如果你只需要一个字符数组:

arr = list(str)

如果你想用一个特定的分隔符分隔str:

# str = "temp//temps" will will be ['temp', 'temps']
arr = str.split("//")

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']

要分割字符串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)将使你的列表恢复到以前的字符串形式…