简体   繁体   English

如何使用多个分隔符拆分 python 中的字符串

[英]How to split string in python using multiple delimeters

I am using Python3 and wants to split the string into the multiple substrings.我正在使用 Python3 并希望将字符串拆分为多个子字符串。 My code is shown below.我的代码如下所示。

pr_list=re.split(r'\s{1,}', "the string, data,could have,  multiple   spaces".strip())

Above code works fine for single or multiple spaces which comes as a delimiter.上面的代码适用于作为分隔符的单个或多个空格。 But additionally, how can I split the same string using the another delimiter ie ',' as well?但此外,如何使用另一个分隔符(即','拆分相同的字符串?

For eg例如

"data,could" string shown above also split into "data" and "could" string.上面显示的“data,could”字符串也分为“data”和“could”字符串。

Out put i am looking is just the words, with out spaces or ','.输出我正在寻找的只是单词,没有空格或“,”。

['the', 'string', 'data', 'could', 'have', 'multiple', 'spaces']

Maybe you can use this r'[,]+'也许你可以使用这个r'[,]+'

import re

pr_list=re.split(r'[ ,]+', "the string, data,could have,  multiple   spaces".strip())
>>> pr_list
['the', 'string', 'data', 'could', 'have', 'multiple', 'spaces']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM