python-按特殊字符和数字拆分字符串
我有一个要在整数的每个实例中拆分的字符串,除非整数直接后面是另一个整数。然后,我想在“(”和“)”上拆分相同的字符串。
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您必须使用 tramece set 要获得想要的东西,更改
(\ code>)(\ code>(\ \) d+)
to this([\ d]+| [\(\)])
输出:
您还必须匹配
()
字符,没有它将打印(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]+|[\(\)])
Output:
You also have to match the
()
characters and without it will print(O
, and sincere.split
returns a list with empty value(s), just remove itWith
([\d]+|[A-Z])
will work too but re.split will return more empty strings in the list