python-按特殊字符和数字拆分字符串

发布于 2025-02-13 11:21:32 字数 560 浏览 1 评论 0原文

我有一个要在整数的每个实例中拆分的字符串,除非整数直接后面是另一个整数。然后,我想在“(”和“)”上拆分相同的字符串。

myStr = ("H12(O1H2)2O2C1")
list1 = re.split('(\d+)', myStr)
print(list1)
list1 = re.split('(\W)', myStr)
print(list1)

我希望结果是['h','12','(','o','1','h','2','2','),'2','o','2' ,'c','1']。

之后:

re.split('(\d+)', myStr)

我得到:

['H', '12', '(O', '1', 'H', '2', ')', '2', 'O', '2', 'C', '1']

我现在想将开放式括号和“ O”分开以制成单个元素。 在列表已经按照我尝试的方式拆分后,试图将其拆分。 另外,“ MyStr”最终将是用户输入,因此我认为通过已知字符串索引(例如在此示例中)会解决我的问题。 对建议开放。

I have a string that I want to split at every instance of an integer, unless an integer is directly followed by another integer. I then want to split that same string at "(" and ")".

myStr = ("H12(O1H2)2O2C1")
list1 = re.split('(\d+)', myStr)
print(list1)
list1 = re.split('(\W)', myStr)
print(list1)

I want the result to be ['H', '12', '(', 'O', '1', 'H', '2', ')', '2', 'O', '2', 'C', '1'].

After:

re.split('(\d+)', myStr)

I get:

['H', '12', '(O', '1', 'H', '2', ')', '2', 'O', '2', 'C', '1']

I now want to split up the open parenthesis and the "O" to make individual elements.
Trying to split up a list after it's already been split up the way I tried doesn't work.
Also, "myStr" eventually will be a user input, so I don't think that indexing through a known string (like myStr is in this example) would solve my issue.
Open to suggestions.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

小苏打饼 2025-02-20 11:21:32

您必须使用 tramece set 要获得想要的东西,更改(\ code>)(\ code>(\ \) d+) to this ([\ d]+| [\(\)])

import re

myStr = ("H12(O1H2)2O2C12")
list1 = re.split('([\d]+|[\(\)])', myStr)
# print(list1)

noempty_list = list(filter(None, list1))
print(noempty_list)

输出:

['H', '12', '(', 'O', '1', 'H', '2', ')', '2', 'O', '2', 'C', '1']

您还必须匹配()字符,没有它将打印(o,并且由于re.split返回带有空值的列表,只需删除它

使用([\ d]+| [az])也可以使用,但是re.split将返回列表中的更多空字符串

You have to use character set to get what you want, change (\d+) to something like this ([\d]+|[\(\)])

import re

myStr = ("H12(O1H2)2O2C12")
list1 = re.split('([\d]+|[\(\)])', myStr)
# print(list1)

noempty_list = list(filter(None, list1))
print(noempty_list)

Output:

['H', '12', '(', 'O', '1', 'H', '2', ')', '2', 'O', '2', 'C', '1']

You also have to match the () characters and without it will print (O, and since re.split returns a list with empty value(s), just remove it

With ([\d]+|[A-Z]) will work too but re.split will return more empty strings in the list

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文