如何在 Python 中按 1 次或多次出现的分隔符进行拆分? [英] How can I split by 1 or more occurrences of a delimiter in Python?
问题描述
我有一个来自日志文件的格式化字符串,如下所示:
<预><代码>>>>一个=测试结果"也就是说,测试和结果被一些空格分开 - 它可能是使用格式化字符串创建的,它给了 test
一些恒定的间距.
简单的拆分是行不通的:
<预><代码>>>>a.split(" ")['测试', '', '', '', ... '', '', '', '', '', '', '', '', '', '', '','结果']split(DELIMITER, COUNT)
清除了一些不必要的值:
这有帮助 - 当然,我真的需要:
['test', 'result']
我可以使用 split()
后跟 map
+ strip()
,但我想知道是否有更 Pythonic 的方法
谢谢,
亚当
更新:这么简单的解决方案!谢谢大家.
只是不给任何分隔符?
<预><代码>>>>一个=测试结果">>>a.split()['测试结果']I have a formatted string from a log file, which looks like:
>>> a="test result"
That is, the test and the result are split by some spaces - it was probably created using formatted string which gave test
some constant spacing.
Simple splitting won't do the trick:
>>> a.split(" ")
['test', '', '', '', ... '', '', '', '', '', '', '', '', '', '', '', 'result']
split(DELIMITER, COUNT)
cleared some unnecessary values:
>>> a.split(" ",1)
['test', ' result']
This helped - but of course, I really need:
['test', 'result']
I can use split()
followed by map
+ strip()
, but I wondered if there is a more Pythonic way to do it.
Thanks,
Adam
UPDATE: Such a simple solution! Thank you all.
Just do not give any delimeter?
>>> a="test result"
>>> a.split()
['test', 'result']
这篇关于如何在 Python 中按 1 次或多次出现的分隔符进行拆分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!