Python/Django如何从字符串中删除额外的空格和制表符?

2024-04-27 03:20:29 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
3条回答
>>> import re
>>> re.sub(r'\s+', ' ', 'some   test with     ugly  whitespace')
'some test with ugly whitespace'

在任意空格上拆分,然后在单个空格上连接。

' '.join(s.split())

我将使用Django的slugify方法,它将空格压缩为一个短划线和其他有用的功能:

from django.template.defaultfilters import slugify

相关问题 更多 >