在 Python 中使用多个分隔符拆分字符串 [英] Split string with multiple delimiters in Python

查看:45
本文介绍了在 Python 中使用多个分隔符拆分字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在网上找到了一些答案,但我没有使用正则表达式的经验,我认为这正是这里所需要的.

我有一个字符串需要用 ';' 分割或者 ', '也就是说,它必须是分号或逗号后跟一个空格.没有尾随空格的单个逗号应该保持不变

示例字符串:

"b-阶段二乙烯基硅氧烷-双苯并环丁烯[124221-30-3],均三甲苯[000108-67-8];聚合的1,2-二氢-2,2,4-三甲基喹啉[026780-96-1]"

应拆分为包含以下内容的列表:

('b-阶段二乙烯基硅氧烷-双-苯并环丁烯[124221-30-3]','均三甲苯[000108-67-8]','聚合的1,2-二氢-2,2,4-三甲基喹啉 [026780-96-1]')

解决方案

幸运的是,Python 内置了这个 :)

导入重新re.split('; |, ',str)

更新:
关注您的评论:

<预><代码>>>>a='美丽,是;更好*比 ugly'>>>进口重新>>>re.split('; |, |*| ',a)['美丽','是','更好','比','丑']

I found some answers online, but I have no experience with regular expressions, which I believe is what is needed here.

I have a string that needs to be split by either a ';' or ', ' That is, it has to be either a semicolon or a comma followed by a space. Individual commas without trailing spaces should be left untouched

Example string:

"b-staged divinylsiloxane-bis-benzocyclobutene [124221-30-3], mesitylene [000108-67-8]; polymerized 1,2-dihydro-2,2,4- trimethyl quinoline [026780-96-1]"

should be split into a list containing the following:

('b-staged divinylsiloxane-bis-benzocyclobutene [124221-30-3]' , 'mesitylene [000108-67-8]', 'polymerized 1,2-dihydro-2,2,4- trimethyl quinoline [026780-96-1]') 

解决方案

Luckily, Python has this built-in :)

import re
re.split('; |, ',str)

Update:
Following your comment:

>>> a='Beautiful, is; better*than
ugly'
>>> import re
>>> re.split('; |, |*|
',a)
['Beautiful', 'is', 'better', 'than', 'ugly']

这篇关于在 Python 中使用多个分隔符拆分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆