![](/img/trans.png)
[英]How to Split a comma separated string of dictionaries into a Pandas dataframe
[英]How to split string separated by a comma within the bracket
我正在尝试拆分用括号分隔的字符串
例如,我有这个字符串:
2021_02_25_{1,2,3,4}_stackoverflow
我想提取括号 {} 内的字符串,然后用逗号将其拆分,因此 output 将是:
[1, 2, 3, 4]
使用 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']
如果你想要一个integer
列表:
In [77]: list(map(int, s[s.find("{")+1:s.find("}")].split(',')))
Out[77]: [1, 2, 3, 4]
我们可以在这里使用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']]
请注意,此答案对于输入字符串中可能有多个{...}
术语是稳健的。 如果没有,那么只需访问上面的二维列表output
的第一个元素即可获得答案。
你可以试试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.