Python 如何将字符串拆分为字符数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4978787/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to split a string into array of characters?
提问by Adrian
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?
str.split(//)似乎不像 Ruby 那样工作。有没有一种简单的方法可以不循环地做到这一点?
回答by Senthil Kumaran
You take the string and pass it to list()
您获取字符串并将其传递给 list()
s = "mystring"
l = list(s)
print l
回答by Sylvain
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
回答by Alexey Milogradov
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 mapand lambdafunction. It may be appropriate for more complex tasks:
第二个用途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']
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 docsfor more methods
有关更多方法,请参阅python 文档
回答by John Lockwood
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):
好吧,尽管我喜欢 list(s) 版本,但这是我发现的另一种更详细的方式(但它很酷,所以我想我会把它添加到战斗中):
>>> 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']
回答by Lewis James-Odwin
You can also do it in this very simple way without list():
您也可以在没有 list() 的情况下以这种非常简单的方式执行此操作:
>>> [c for c in "foobar"]
['f', 'o', 'o', 'b', 'a', 'r']
回答by Abass Sesay
>>> 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.
其中 a 是您要分离的字符串。值“a[i]”是可以附加到列表的字符串的单个字符。
回答by vaultah
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.
但仍然有更短的解决方案可以做同样的事情。
listconstructor can be used to convert any iterable(iterators, lists, tuples, string etc.) to list.
list构造函数可用于将任何可迭代对象(迭代器、列表、元组、字符串等)转换为列表。
>>> list('abc')
['a', 'b', 'c']
The big plus is that it works the same in both Python 2 and Python 3.
最大的优点是它在 Python 2 和 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:
此外,从 Python 3.5 开始(感谢出色的PEP 448),现在可以通过将任何可迭代对象解包为空列表文字来构建列表:
>>> [*'abc']
['a', 'b', 'c']
This is neater, and in some cases more efficient than calling listconstructor directly.
这更简洁,在某些情况下比list直接调用构造函数更有效。
I'd advise against using map-based approaches, because mapdoes notreturn a list in Python 3. See How to use filter, map, and reduce in Python 3.
我建议不要使用map基于方法,因为在 Python 3map中不返回列表。请参阅如何在 Python 3中使用过滤器、映射和缩减。
回答by Sid
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循环:
for c in uhello:
print(c)
Output:
输出:
H
e
l
l
o
W
o
r
l
d
回答by minggli
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.
类似于list(string)但返回一个在使用点延迟评估的生成器,因此内存效率高。

