python - Python: how to split string by groups Alpha-numeric vs numeric
问题描述
Lets say I have Strings like:
"H39_M1", "H3_M15", "H3M19", "H3M11", "D363_H3", "D_128_H17_M50"
How can I split them every single one into a list of substrings? like this:
["H39", "M1"], "[H3, "Min15"], ["H3","M19"], ["H3","M11"], ["D363","H3"], ["D128","H17","M50"]
and afterwards: switch places of alphanumeric-group and numeric group,
like this:
["39H", "1M"], "[3H, "15Min"], ["3H","19M"], ["3H","11M"], ["363D","3H"],["128D","17H","50M"]
length of numbers-group and of alphanumeric group varys as you can see. also "_" underscores can divide them.
解决方案
我可能会建议re.findall
在这里使用re.sub
:
inp = "H3M19"
inp = re.sub(r'([A-Z]+)([0-9]+)', r'\2\1', inp)
parts = re.findall(r'[0-9]+[A-Z]+', inp)
print(parts)
这打印:
['3H', '19M']
第一步re.sub
转换H3M19
为3H19M
, 通过捕获字母和数字对然后交换它们。然后,我们使用re.findall
在交换的输入中查找所有数字/字母对。
推荐阅读
- json - 从固定的 JSON 结构中提取键名
- rust - 有没有办法不释放在条件分支中创建的临时变量,只用堆栈帧销毁它们?
- javascript - 如何在materializecss和angular中设置多项选择的值
- autohotkey - 为什么我的文件追加了一个新行,而我没有指定它?
- typo3 - TYPO3 DBAL Querybuilder:嵌套的 SELECT 语句?
- google-cloud-platform - 我应该使用哪个 Google 云实例来部署一个简单的动态网站
- ada - GNAT重新编译Libray文件/如何强制重新编译所有
- php - 如何修复我的错误并让我的 Adyen Drop In Web 正常工作?
- python-3.x - Vega-Lite 的一些预测在 Altair 中不起作用
- python - 使用带有自定义前缀的when_提到的问题