我有下一个代码:
can="p1=a b c p2=d e f g"
new = can.split()
print(new)
当我执行上面的操作时,我得到了下一个:
['p1=a', 'b', 'c', 'p2=d', 'e', 'f', 'g']
但我真正需要的是:
['p1=a b c', 'p2=d e f g']
a b c
是p1
的值,d e f g
是p2
的值,我该如何实现目标?谢谢!
如果你想要
['p1=a b c', 'p2=d e f g']
,你可以使用正则表达式进行分割:
import re
new = re.split(r'\s+(?=\w+=)', can)
如果您想要字典
{'p1': 'a b c', 'p2': 'd e f g'}
,请进一步拆分=
:
import re
new = dict(x.split('=', 1) for x in re.split(r'\s+(?=\w+=)', can))
您可以匹配您想要的结果,查找变量名称,然后等于和字符,直到找到另一个变量名称和等于,或行尾:
import re
can="p1=a b c p2=d e f g"
re.findall(r'\w+=.*?(?=\s*\w+=|$)', can)
输出:
['p1=a b c', 'p2=d e f g']