基于空格和()拆分字符串

时间:2018-03-27 12:36:48

标签: python string split

需要根据空格和()拆分字符串。 比如说:

输入字符串if condition or (condition-1 or condition-2) then print"

输出应分为:  'if', 'condition', 'or', '(condition-1 or condition-2)', 'then', 'print'.

当我执行str.split()时,即使()中的值也会根据空格进行拆分。

2 个答案:

答案 0 :(得分:1)

也许你可以检查paranthesis和介于两者之间的东西,然后将该部分复制到另一个变量并从原始变量中删除它。然后只需拆分第一个变量并将两个变量加在一起。为此,我将使用re模块。 python documentingAutomate the boring stuff with python

我就这样做了:

import re
statement = input(":")
bracketsearcher = re.compile(r'\(\w+\s\w+\)')
bracketplaces = bracketsearcher.findall(statement)
rest = bracketsearcher.sub('',statement)
print (bracketplaces)
rest = rest.split(" ")
print (rest)

答案 1 :(得分:1)

s = "if condition or (condition-1 or condition-2) then print and (this)"

my_list = list()

while (("(") in s):
    my_list.append(s[s.find('(') : (s.find(')')+1)])
    s = (s[ : (s.find('('))]) + (s[s.find(')')+1 : ])

my_list= my_list + (s.split(' '))

print(my_list)
相关问题