如何将字符串拆分为字符数组?

问题:如何将字符串拆分为字符数组?

我试图在网上四处寻找将字符串拆分为字符数组的答案,但似乎找不到一个简单的方法

str.split(//)似乎不像Ruby那样工作。有没有一种简单的方法可以不循环?

I’ve tried to look around the web for answers to splitting a string into an array of characters but I can’t seem to find a simple method

str.split(//) does not seem to work like Ruby does. Is there a simple way of doing this without looping?


回答 0

>>> s = "foobar"
>>> list(s)
['f', 'o', 'o', 'b', 'a', 'r']

你需要清单

>>> s = "foobar"
>>> list(s)
['f', 'o', 'o', 'b', 'a', 'r']

You need list


回答 1

您将字符串传递给list()

s = "mystring"
l = list(s)
print l

You take the string and pass it to list()

s = "mystring"
l = list(s)
print l

回答 2

您也可以不用list()来以非常简单的方式进行操作:

>>> [c for c in "foobar"]
['f', 'o', 'o', 'b', 'a', 'r']

You can also do it in this very simple way without list():

>>> [c for c in "foobar"]
['f', 'o', 'o', 'b', 'a', 'r']

回答 3

如果您想一次处理您的字符串一个字符。您有多种选择。

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

If you want to process your String one character at a time. you have various options.

uhello = u'Hello\u0020World'

Using List comprehension:

print([x for x in uhello])

Output:

['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']

Using map:

print(list(map(lambda c2: c2, uhello)))

Output:

['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']

Calling Built in list function:

print(list(uhello))

Output:

['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']

Using for loop:

for c in uhello:
    print(c)

Output:

H
e
l
l
o

W
o
r
l
d

回答 4

我探索了完成此任务的另外两种方法。这可能对某人有帮助。

第一个很简单:

In [25]: a = []
In [26]: s = 'foobar'
In [27]: a += s
In [28]: a
Out[28]: ['f', 'o', 'o', 'b', 'a', 'r']

以及第二个用途maplambda功能。它可能适用于更复杂的任务:

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文档

I explored another two ways to accomplish this task. It may be helpful for someone.

The first one is easy:

In [25]: a = []
In [26]: s = 'foobar'
In [27]: a += s
In [28]: a
Out[28]: ['f', 'o', 'o', 'b', 'a', 'r']

And the second one use map and lambda function. It may be appropriate for more complex tasks:

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

For example

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

See python docs for more methods


回答 5

任务归结为遍历字符串中的字符并将它们收集到列表中。最幼稚的解决方案看起来像

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基于方法的方法,因为map不会在Python 3中返回列表。请参见如何在Python 3 中使用过滤,映射和精简

The task boils down to iterating over characters of the string and collecting them into a list. The most naïve solution would look like

result = []
for character in string:
    result.append(character)

Of course, it can be shortened to just

result = [character for character in string]

but there still are shorter solutions that do the same thing.

list constructor can be used to convert any iterable (iterators, lists, tuples, string etc.) to list.

>>> list('abc')
['a', 'b', 'c']

The big plus is that it works the same in both Python 2 and Python 3.

Also, starting from Python 3.5 (thanks to the awesome PEP 448) it’s now possible to build a list from any iterable by unpacking it to an empty list literal:

>>> [*'abc']
['a', 'b', 'c']

This is neater, and in some cases more efficient than calling list constructor directly.

I’d advise against using map-based approaches, because map does not return a list in Python 3. See How to use filter, map, and reduce in Python 3.


回答 6

我只需要一个字符数组:

arr = list(str)

如果要用特定的str拆分str:

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

I you just need an array of chars:

arr = list(str)

If you want to split the str by a particular str:

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

回答 7

split()内置函数将仅根据特定条件分隔值,但在单个单词中,它无法满足条件。因此,可以借助来解决list()。它在内部调用Array,它将基于数组存储值。

假设,

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

split() inbuilt function will only separate the value on the basis of certain condition but in the single word, it cannot fulfill the condition. So, it can be solved with the help of list(). It internally calls the Array and it will store the value on the basis of an array.

Suppose,

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

回答 8

打开包装:

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

Unpack them:

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

回答 9

如果您希望只读访问该字符串,则可以直接使用数组符号。

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'

在不使用正则表达式的情况下可能对测试很有用。字符串是否包含结尾换行符?

>>> t[-1] == '\n'
False
>>> t = 'my string\n'
>>> t[-1] == '\n'
True

If you wish to read only access to the string you can use array notation directly.

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'

Could be useful for testing without using regexp. Does the string contain an ending newline?

>>> t[-1] == '\n'
False
>>> t = 'my string\n'
>>> t[-1] == '\n'
True

回答 10

好吧,就像我喜欢列表版本一样,这是我发现的另一种更为冗长的方式(但它很酷,所以我认为我应该将其添加到列表中):

>>> text = "My hovercraft is full of eels"
>>> [text[i] for i in range(len(text))]
['M', 'y', ' ', 'h', 'o', 'v', 'e', 'r', 'c', 'r', 'a', 'f', 't', ' ', 'i', 's', ' ', 'f', 'u', 'l', 'l', ' ', 'o', 'f', ' ', 'e', 'e', 'l', 's']

Well, much as I like the list(s) version, here’s another more verbose way I found (but it’s cool so I thought I’d add it to the fray):

>>> text = "My hovercraft is full of eels"
>>> [text[i] for i in range(len(text))]
['M', 'y', ' ', 'h', 'o', 'v', 'e', 'r', 'c', 'r', 'a', 'f', 't', ' ', 'i', 's', ' ', 'f', 'u', 'l', 'l', ' ', 'o', 'f', ' ', 'e', 'e', 'l', 's']

回答 11

from itertools import chain

string = 'your string'
chain(string)

list(string)生成器类似,但返回在使用时延迟评估的生成器,因此内存效率高。

from itertools import chain

string = 'your string'
chain(string)

similar to list(string) but returns a generator that is lazily evaluated at point of use, so memory efficient.


回答 12

>>> for i in range(len(a)):
...     print a[i]
... 

其中a是您要分离的字符串。值“ a [i]”是字符串的各个字符,可以将它们附加到列表中。

>>> for i in range(len(a)):
...     print a[i]
... 

where a is the string that you want to separate out. The values “a[i]” are the individual character of the the string these could be appended to a list.