[英]Conditionally Splitting a String in Python
I have a string that looks like this: 我有一个看起来像这样的字符串:
Increase (decrease) 1,334 ( 2,921) 2,797
I'd like to split the string to look like this: 我想将字符串拆分为如下所示:
['Increase (decrease)', '1,334', '(2,921)', '2,797']
I've tried: 我试过了:
item=re.split(r'\s{3,}', strg)
But clearly this yields: 但显然这会产生:
['Increase (decrease)', '1,334', '(', '2,921)', '2,797']
Any help would be greatly appreciated. 任何帮助将不胜感激。
I would remove all spaces after an opening parenthesis and then split: 我会删除一个左括号后的所有空格然后拆分:
>>> re.split(r'\s{3,}', re.sub(r"(?<=\()\s+", "", s))
['Increase (decrease)', '1,334', '(2,921)', '2,797']
Note that (?<=\\()
is a positive lookbehind . 请注意
(?<=\\()
是一个积极的看法 。
You can replace the spaces between parenthesis and then split: 您可以替换括号之间的空格然后拆分:
>>> re.split(r'\s{3,}',re.sub(r'(?<=\()\s+','',s))
['Increase (decrease)', '1,334', '(2,921)', '2,797']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.