简体   繁体   English

在第二次出现逗号时拆分字符串

[英]Split a string at second occurence of Comma

My string is like below: 我的字符串如下所示:

Str=S1('amm','string'),S2('amm_sec','string'),S3('amm_','string')

How can I Split the string so that my str_list item becomes: 如何分割字符串,以便我的str_list项变为:

Str_List[0]=S1('amm','string')
Str_List[1]=S2('amm_sec','string') 
...

If I use Str.split(',') then the output is: 如果我使用Str.split(',')则输出为:

Str_List[0]=S1('amm'
...

you can use regex with re in python 您可以在python中将regex与re一起使用

import re
Str = "S1('amm','string'),S2('amm_sec','string'),S3('amm_','string')"
lst = re.findall("S\d\(.*?\)", Str)

this will give you: 这将为您提供:

["S1('amm','string')", "S2('amm_sec','string')", "S3('amm_','string')"]

to explain the regex a little more: 多解释一下正则表达式:

S first you match 'S' S首先你匹配“S”

\\d next look for a digit \\d接下来寻找一个数字

\\( then the '(' character \\(然后是'('字符

.*? with any number of characters in the middle (but match as few as you can) 中间有任意数量的字符(但要尽可能少地匹配)

\\) followed by the last ')' character \\)后跟最后一个')'字符

you can play with the regex a little more here 你可以在这里玩正则表达式

My first thought would be to replace ',S' with ' S' using regex and split on spaces. 我的第一个想法是使用正则表达式将',S'替换为' S'并在空格处分割。

import re
Str = re.sub(',S',' S',Str)
Str_list = Str.split()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM