社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

如何使用Python RE从字符串中删除多余的换行符和制表符

Winston • 3 年前 • 1329 次点击  

给定一个Python字符串,例如:

"good \nand bad and\n\t not great and awesome"

我想把它分成一个数组 and s、 同时也移除了杂散的 \n 还有 \t s:

["good", "bad", "not great", "awesome"]

如何使用 re.split() ?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/130632
 
1329 次点击  
文章 [ 2 ]  |  最新文章 3 年前
Hasidul Islam
Reply   •   1 楼
Hasidul Islam    3 年前

你可以试试这个。

s = "good \nand bad and\n\t not great and awesome"
s = s.replace('\n','').replace('\t','')
s_list = s.split('and')
Tim Biegeleisen
Reply   •   2 楼
Tim Biegeleisen    3 年前

这里是一种正则表达式拆分方法。我们可以试着分开 \s+and\s+ ,目标是 and 两边都是空白。请注意,制表符和换行符是空白字符,包含在 \s .

inp = "good \nand bad and\n\t not great and awesome"
parts = re.split(r'\s+and\s+', inp)
print(parts)  # ['good', 'bad', 'not great', 'awesome']