[英]How to split string separated by a comma within the bracket
I'm trying to split a string separated withing a bracket我正在尝试拆分用括号分隔的字符串
for example, I have this string:例如,我有这个字符串:
2021_02_25_{1,2,3,4}_stackoverflow
I want to extract the string inside the brackets {} and then split it by comma so the output would be:我想提取括号 {} 内的字符串,然后用逗号将其拆分,因此 output 将是:
[1, 2, 3, 4]
Use String's find
method:使用 String 的
find
方法:
In [68]: s = '2021_02_25_{1,2,3,4}_stackoverflow'
In [75]: s[s.find("{")+1:s.find("}")].split(',')
Out[75]: ['1', '2', '3', '4']
If you want an integer
list :如果你想要一个
integer
列表:
In [77]: list(map(int, s[s.find("{")+1:s.find("}")].split(',')))
Out[77]: [1, 2, 3, 4]
We can use re.findall
here:我们可以在这里使用
re.findall
:
inp = "2021_02_25_{1,2,3,4}_stackoverflow"
matches = re.findall(r'\{(.*?)\}', inp)
output = [x.split(',') for x in matches]
print(output) # [['1', '2', '3', '4']]
Note that this answer is robust to there possibly being more than one {...}
term in the input string.请注意,此答案对于输入字符串中可能有多个
{...}
术语是稳健的。 If not, then just access the first element of the 2D list output
above to get your answer.如果没有,那么只需访问上面的二维列表
output
的第一个元素即可获得答案。
You can try regular expression
你可以试试
regular expression
import re
s = '2021_02_25_{1,2,3,4}_stackoverflow'
output = [int(i) for i in re.findall(r'{(\d(?:,\d)+)}', s)[0].split(',')]
print(output)
[1, 2, 3, 4]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.