去除空格/制表符/换行符-python [英] Strip spaces/tabs/newlines - python

查看:121
本文介绍了去除空格/制表符/换行符-python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我写了这个,应该可以:

myString="我想删除所有白色 \t 空格、新行 \n 和制表符 \t"myString = myString.strip(' \n\t')打印 myString

输出:

我想删除所有空格,新行和标签

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

解决方案

Use str.split([sep[, maxsplit]]) 没有 sep>sep=无:

来自文档:

<块引用>

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

演示:

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

在返回的列表上使用 str.join 得到这个输出:

<预><代码>>>>' '.join(myString.split())'我想删除所有空格、新行和制表符'

I am trying to remove all spaces/tabs/newlines in python 2.7 on Linux.

I wrote this, that should do the job:

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

output:

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

It seems like a simple thing to do, yet I am missing here something. Should I be importing something?

解决方案

Use str.split([sep[, maxsplit]]) with no sep or sep=None:

From docs:

If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace.

Demo:

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

Use str.join on the returned list to get this output:

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

这篇关于去除空格/制表符/换行符-python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆