去除空格/制表符/换行符-python [英] Strip spaces/tabs/newlines - 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
得到这个输出:
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 isNone
, 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屋!