我的字符串是象下面这样:拆分以逗号
Str=S1('amm','string'),S2('amm_sec','string'),S3('amm_','string')
我如何可以分割字符串,以便我为str_list项变为:
Str_List[0]=S1('amm','string')
Str_List[1]=S2('amm_sec','string')
...
如果我使用Str.split(',')
则输出是:
Str_List[0]=S1('amm'
...
我的字符串是象下面这样:拆分以逗号
Str=S1('amm','string'),S2('amm_sec','string'),S3('amm_','string')
我如何可以分割字符串,以便我为str_list项变为:
Str_List[0]=S1('amm','string')
Str_List[1]=S2('amm_sec','string')
...
如果我使用Str.split(',')
则输出是:
Str_List[0]=S1('amm'
...
我首先想到的是将',S'
替换为' S'
使用正则表达式和拆分空间上。
import re
Str = re.sub(',S',' S',Str)
Str_list = Str.split()
嗨..感谢您的关注和帮助。我现在能够分裂。但现在得到另一个问题: – Shikha
嗨..谢谢你看看,并帮助解决。我现在能够分裂。但是现在又出现了另一个问题:SchematicField('amm_report_row','string')“,” SchemaField('amm_subsection_row','float')“,”SchemaField('amm_subsection _desc','string')“] 和SCHEMA [0]给了我SCHEMA [0] = SchemaField('amm_reporting_row','string')等等 但我需要数组没有双引号和数组的每个元素在新行。 如果双引号可以删除,那么它将是正确的。 – Shikha
是SchemaField的一个函数吗?你想要一个函数调用列表吗? –
你可以在Python中使用正则表达式与re
import re
Str = "S1('amm','string'),S2('amm_sec','string'),S3('amm_','string')"
lst = re.findall("S\d\(.*?\)", Str)
这会给你:
["S1('amm','string')", "S2('amm_sec','string')", "S3('amm_','string')"]
解释正则表达式多一点:
S
首先你匹配'S'
\d
接下来看一个数字
\(
然后在中间任意数量的字符的“(”字符
.*?
(但匹配尽可能少的也可以),然后最后
\)
“)”字符
你可以用正则表达式多一点here
我建议用'\ w +'替换'S \ d'来更通用。 –
请格式化你的代码打,因为我t代表,它是不可读的。另外,你几乎可以肯定地讨论* python lists * not * python arrays *。 –
你的字符串应该在引号中。按原样,这会尝试将'S1'作为函数应用,并且即使定义了语法错误也会给出语法错误。 –
这个字符串从哪里来?像'amm''这样的内部字符串是否可以包含引号或逗号? –