[英]String splitting python
I am trying to parse a file and split the line in python. 我正在尝试解析文件并在python中拆分行。 Currently i can parse the file and load it into a list. 目前,我可以解析文件并将其加载到列表中。
I am trying to take each line and split it by the parenthesis, 我试图将每一行都用括号括起来,
'datediff(varchar(30),timestamp(3),timestamp(3))'
reverse(text)
checkcluster(int,int,int,int,int)
declaredown(int)
I am trying to extract the parameters in side the function as so: 我正在尝试提取函数中的参数,如下所示:
['varchar(30),timestamp(3),timestamp(3)','text','int,int,int,int,int','int']
However the result i am getting is: 但是我得到的结果是:
['varchar(30', 'text', 'int,int,int,int,int', 'int']
I believe its because of bracket in varchar. 我相信这是因为varchar中的括号。 Is there a way to split it just by the first occurrence and last occurrence of parenthesis? 有没有一种方法可以仅通过括号的第一个出现和最后一个出现来拆分它?
Is there a way to split it just by the first occurrence and last occurrence of parenthesis? 有没有一种方法可以仅通过括号的第一个出现和最后一个出现来拆分它?
Yes, use partition
and rpartition
. 是的,使用partition
和rpartition
。
>>> s = 'datediff(varchar(30),timestamp(3),timestamp(3))'
>>> s.partition("(")
('datediff', '(', 'varchar(30),timestamp(3),timestamp(3))')
>>> s.partition("(")[2]
'varchar(30),timestamp(3),timestamp(3))'
>>> s.partition("(")[2].rpartition(")")
('varchar(30),timestamp(3),timestamp(3)', ')', '')
>>> s.partition("(")[2].rpartition(")")[0]
'varchar(30),timestamp(3),timestamp(3)'
>>> def extract(s):
... return s.partition("(")[2].rpartition(")")[0]
...
>>> print(extract('datediff(varchar(30),timestamp(3),timestamp(3))'))
varchar(30),timestamp(3),timestamp(3)
>>> print(extract('reverse(text)'))
text
>>> print(extract('checkcluster(int,int,int,int,int)'))
int,int,int,int,int
>>> print(extract('declaredown(int)'))
int
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.