如何在 Python 中使用空分隔符拆分字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17380592/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:03:05  来源:igfitidea点击:

How to split a string using an empty separator in Python

pythonstringsplit

提问by Saullo G. P. Castro

What is a good way to do some_string.split('')in python? This syntax gives an error:

some_string.split('')在 python 中做什么的好方法是什么?此语法给出了错误:

a = '1111'
a.split('')

ValueError: empty separator

I would like to obtain:

我想获得:

['1', '1', '1', '1']

采纳答案by TerryA

Use list():

使用list()

>>> list('1111')
['1', '1', '1', '1']

Alternatively, you can use map()(Python 2.7 only):

或者,您可以使用map()(仅限 Python 2.7):

>>> map(None, '1111')
['1', '1', '1', '1']

Time differences:

时差:

$ python -m timeit "list('1111')"
1000000 loops, best of 3: 0.483 usec per loop
$ python -m timeit "map(None, '1111')"
1000000 loops, best of 3: 0.431 usec per loop

回答by oleg

One can cast strings to list directly

可以直接将字符串转换为列表

>>> list('1111')
['1', '1', '1', '1']

or using list comprehensions

或使用列表理解

>>> [i for i in '1111']
['1', '1', '1', '1']

second way can be useful if one wants to split strings for substrings more than 1 symbol length

如果想要为超过 1 个符号长度的子字符串拆分字符串,则第二种方法可能很有用

>>> some_string = '12345'
>>> [some_string[i:i+2] for i in range(0, len(some_string), 2)]
['12', '34', '5']

回答by Lennart Regebro

Strings are iterables and can be indexed, hence you don't really need to split it at all:

字符串是可迭代的并且可以被索引,因此你根本不需要拆分它:

>>> for char in '11111':
...   print char
... 
1
1
1
1
1
>>> '11111'[4]
'1'

You can "split" it with a call to list, but it doesn't make much difference:

您可以通过调用 list 来“拆分”它,但这并没有太大区别:

>>> for char in list('11111'):
...   print char
... 
1
1
1
1
1
>>> list('11111')[4]
'1'

So you only need to do this if your code explicitly expects a list. For example:

因此,只有当您的代码明确需要一个列表时,您才需要这样做。例如:

>>> list('11111').append('2')
>>> l = list('11111')
>>> l.append(2)
>>> l
['1', '1', '1', '1', '1', 2]

This doesn't work with a straight string:

这不适用于直字符串:

>>> l.append('2')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'append'

In that case you would need:

在这种情况下,您将需要:

>>> l += '2'
>>> l
'111112'

回答by Amalraj Victory

Method #1:

方法#1:

s="Amalraj"
l=[i for i in s]
print(l)

Output:

输出:

['A', 'm', 'a', 'l', 'r', 'a', 'j']

Method #2:

方法#2:

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

Output:

输出:

['A', 'm', 'a', 'l', 'r', 'a', 'j']

Method #3:

方法#3:

import re; # importing regular expression module
s="Amalraj"
l=re.findall('.',s)
print(l)

Output:

输出:

['A', 'm', 'a', 'l', 'r', 'a', 'j']