Python/Django:如何从字符串中删除多余的空格和制表符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4241757/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python/Django: How to remove extra white spaces & tabs from a string?
提问by Continuation
I'm building a website with Python/Django. Users submit tags. Each tag can contain multiple words. Each tag has an ID number. I want to make sure tags that are formatted slightly differently are still being recognized as the same tag.
我正在用 Python/Django 构建一个网站。用户提交标签。每个标签可以包含多个单词。每个标签都有一个 ID 号。我想确保格式略有不同的标签仍然被识别为相同的标签。
For example, if one user submitted the tag "electric guitar" and the other submitted "electric guitar" (2 white spaces between the 2 words) I want to be able to recognize they are the same tag.
例如,如果一个用户提交了“电吉他”标签,另一个用户提交了“电吉他”(2 个单词之间的 2 个空格),我希望能够识别它们是同一个标签。
How to I remove all the extra white spaces and tabs in this case? Thanks.
在这种情况下,如何删除所有额外的空格和制表符?谢谢。
采纳答案by Ignacio Vazquez-Abrams
Split on any whitespace, then join on a single space.
在任何空白处拆分,然后在一个空白处加入。
' '.join(s.split())
回答by Marcus Whybrow
I would use Django's slugifymethod, which condenses spaces into a single dash and other helpful features:
我会使用 Django 的slugify方法,它将空格压缩为一个破折号和其他有用的功能:
from django.template.defaultfilters import slugify
回答by nmichaels
"electric guitar".split()will give you ['electric', 'guitar']. So will "electric \tguitar".
"electric guitar".split()会给你['electric', 'guitar']。也会"electric \tguitar"。
回答by ThiefMaster
>>> import re
>>> re.sub(r'\s+', ' ', 'some test with ugly whitespace')
'some test with ugly whitespace'
回答by Deepak 'Kaseriya'
There could be many white spaces like below:
可能有很多空格,如下所示:
var = " This is the example of how to remove spaces "
Just do simple task like, use replace function:
只需执行简单的任务,例如使用替换功能:
realVar = var.replace(" ",'')
Now the outpur would be:
现在输出将是:
Thisistheexampleofhowtoremovespaces
Just Chill......... :-)
冷静一下....... :-)
回答by zzart
This function removes everything which is not digit in a string. I use it all over the place.
此函数删除字符串中非数字的所有内容。我到处使用它。
def parseInt(string):
if isinstance(string, (str, int, unicode)):
try:
digit = int(''.join([x for x in string if x.isdigit() ]))
except ValueError:
return False
else:
return digit
else:
return False

