繁体   English   中英

去除空格/制表符/换行符-python

[英]Strip spaces/tabs/newlines - python

我试图在 Linux 上的 python 2.7 中删除所有空格/制表符/换行符。

我写了这个,应该可以完成这项工作:

myString="I want to Remove all white \t spaces, new lines \n and tabs \t"
myString = myString.strip(' \n\t')
print myString

输出:

I want to Remove all white   spaces, new lines 
 and tabs

这似乎是一件简单的事情,但我在这里遗漏了一些东西。 我应该进口一些东西吗?

使用str.split([sep[, maxsplit]])没有sepsep=None

文档

如果sep未指定或为None ,则应用不同的拆分算法:连续空格的运行被视为单个分隔符,如果字符串具有前导或尾随空格,则结果将在开头或结尾不包含空字符串。

演示:

>>> myString.split()
['I', 'want', 'to', 'Remove', 'all', 'white', 'spaces,', 'new', 'lines', 'and', 'tabs']

在返回的列表上使用str.join以获取此输出:

>>> ' '.join(myString.split())
'I want to Remove all white spaces, new lines and tabs'

如果要删除多个空格项并用单个空格替换它们,最简单的方法是使用这样的正则表达式:

>>> import re
>>> myString="I want to Remove all white \t spaces, new lines \n and tabs \t"
>>> re.sub('\s+',' ',myString)
'I want to Remove all white spaces, new lines and tabs '

如果需要,您可以使用.strip()删除尾随空格。

使用re

import re
myString = "I want to Remove all white \t spaces, new lines \n and tabs \t"
myString = re.sub(r"[\n\t\s]*", "", myString)
print myString

输出:

我想删除所有空格、换行符和制表符

这只会删除制表符、换行符、空格和其他任何内容。

import re
myString = "I want to Remove all white \t spaces, new lines \n and tabs \t"
output   = re.sub(r"[\n\t\s]*", "", myString)

输出:

我想删除所有空白、换行符和制表符

再会!

import re

mystr = "I want to Remove all white \t spaces, new lines \n and tabs \t"
print re.sub(r"\W", "", mystr)

Output : IwanttoRemoveallwhitespacesnewlinesandtabs

上述建议使用正则表达式的解决方案并不理想,因为这是一个很小的任务,正则表达式需要的资源开销比任务的简单性所证明的要多。

这是我所做的:

myString = myString.replace(' ', '').replace('\\t', '').replace('\\n', '')

或者如果你有一堆东西要删除,以至于单行解决方案会很长:

removal_list = [' ', '\t', '\n']
for s in removal_list:
  myString = myString.replace(s, '')

由于没有什么比这更复杂的了,我想分享它,因为它帮助了我。

这是我最初使用的:

import requests
import re

url = 'https://stackoverflow.com/questions/10711116/strip-spaces-tabs-newlines-python' # noqa
headers = {'user-agent': 'my-app/0.0.1'}
r = requests.get(url, headers=headers)
print("{}".format(r.content))

不希望的结果:

b'<!DOCTYPE html>\r\n\r\n\r\n    <html itemscope itemtype="http://schema.org/QAPage" class="html__responsive">\r\n\r\n    <head>\r\n\r\n        <title>string - Strip spaces/tabs/newlines - python - Stack Overflow</title>\r\n        <link

这是我将其更改为:

import requests
import re

url = 'https://stackoverflow.com/questions/10711116/strip-spaces-tabs-newlines-python' # noqa
headers = {'user-agent': 'my-app/0.0.1'}
r = requests.get(url, headers=headers)
regex = r'\s+'
print("CNT: {}".format(re.sub(regex, " ", r.content.decode('utf-8'))))

预期结果:

<!DOCTYPE html> <html itemscope itemtype="http://schema.org/QAPage" class="html__responsive"> <head> <title>string - Strip spaces/tabs/newlines - python - Stack Overflow</title>

@MattH 提到的精确正则表达式对我来说是适合我的代码。 谢谢!

注意:这是python3

在连接中使用列表理解的单行怎么样?

>>> foobar = "aaa bbb\t\t\tccc\nddd"
>>> print(foobar)
aaa bbb                 ccc
ddd

>>> print(''.join([c for c in foobar if c not in [' ', '\t', '\n']]))
aaabbbcccddd

暂无
暂无

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

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