字符串在字符串列表中,我想分割?
字符。
例如,将['foo? bar\n', 'baz\n']
拆分为['foo\n', 'bar\n', 'baz\n']
。
(我刚编辑此问题以包含换行符。)
答案 0 :(得分:3)
这是一种方式。
from itertools import chain
x = ['foo? bar', 'baz']
res = list(chain.from_iterable(i.strip().split('?') for i in x))
# ['foo', ' bar', 'baz']
答案 1 :(得分:2)
使用像generator这样的时候,这是相当直接的:
def split_str_in_list(a_list, split_char):
for big_str in a_list:
for s in big_str.split(split_char):
yield s
print(list(split_str_in_list(['foo? bar', 'baz'], '? ')))
['foo', 'bar', 'baz']
答案 2 :(得分:1)
看一个更明确的例子,也许更容易理解。
def split_text(input_list):
result = []
# iterate through every string from input_list
for item in input_list:
#split a string by '? '; splitted is a list with minimum 1 element(item) when item does not contain '? '
splitted = item.split('? ')
# iterate through this list and append every string at result list
for i in splitted:
result.append(i)
return result
input_list = ['foo? bar', 'baz']
print(split_text(input_list))
答案 3 :(得分:0)
您可以尝试这种方法:
df=['foo? bar\n', 'baz\n']
new_list=[]
for i in df:
if '?' in i:
spli_data=i.split('?')
for sub_ in spli_data:
if '\n' not in sub_:
new_list.append(sub_+'\n')
else:
new_list.append(sub_)
else:
new_list.append(i)
输出:
['foo\n', ' bar\n', 'baz\n']