python - 在某些字符之后分割字符串?

标签 python python-3.x

我将得到一个字符串,每次它有“|”、“/”、“.”时我都需要将其拆分。或“_”

我怎样才能快速做到这一点?我知道如何使用命令 split,但是有什么方法可以为其提供超过 1 个分割条件吗?例如,如果给定的输入是

Hello test|multiple|36.strings/just36/testing

我希望输出给出:

"['Hello test', 'multiple', '36', 'strings', 'just36', 'testing']"

最佳答案

使用正则表达式和正则表达式模块:

>>> import re
>>> s='You/can_split|multiple'
>>> re.split(r'[/_|.]', s)
['You', 'can', 'split', 'multiple']

在这种情况下,[/_|.] 将根据这些字符中的任何一个进行拆分。

或者,您可以使用列表理解来插入单个(可能是多个字符)分隔符,然后对其进行拆分:

>>> ''.join(['-><-' if c in '/_|.' else c for c in s]).split('-><-')
['You', 'can', 'split', 'multiple']

添加示例:

>>> s2="Hello test|multiple|36.strings/just36/testing"

方法一:

>>> re.split(r'[/_|.]', s2)
['Hello test', 'multiple', '36', 'strings', 'just36', 'testing']

方法2:

>>> ''.join(['-><-' if c in '/_|.' else c for c in s2]).split('-><-')
['Hello test', 'multiple', '36', 'strings', 'just36', 'testing']

关于python - 在某些字符之后分割字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53217666/

相关文章:

python-3.x - 如何在 zipline 中手动提供基准

.exe 中的 Python 子进程

python - 将字符串的一部分附加到列表中

python - MediaWiki API : can it be used to create new articles programatically?

python - 评估图像分割方法

python - Django一对一字段RelatedObjectDoesNotExist

python - 如何在 Keras Python 中合并多个顺序模型?

python - 什么替代了 Python 3 中的 xreadlines()?

python - 在Scrapy中养CloseSpider有什么影响?

python - 在打印时如何跳过不在字典中的值