#how to trim a multi line string or a file
s=""" line one
\tline two\t
line three """
#line1 starts with a space, #2 starts and ends with a tab, #3 ends with a space.
s1=s.splitlines()
print s1
[' line one', '\tline two\t', 'line three ']
print [i.strip() for i in s1]
['line one', 'line two', 'line three']
#more details:
#we could also have used a forloop from the begining:
for line in s.splitlines():
line=line.strip()
process(line)
#we could also be reading a file line by line.. e.g. my_file=open(filename), or with open(filename) as myfile:
for line in my_file:
line=line.strip()
process(line)
#moot point: note splitlines() removed the newline characters, we can keep them by passing True:
#although split() will then remove them anyway..
s2=s.splitlines(True)
print s2
[' line one\n', '\tline two\t\n', 'line three ']
14 回答
这将从字符串的开头和结尾删除所有空格和换行符:
双方空白:
右侧的空白:
左侧的空白:
正如thedz指出的那样,你可以提供一个参数来将任意字符剥离到这些函数中,如下所示:
这将从字符串的左侧,右侧或两侧剥离任何空格,
\t
,\n
或\r
字符 .上面的示例仅从字符串的左侧和右侧删除字符串 . 如果您还要从字符串中间删除字符,请尝试
re.sub
:那应该打印出来:
Python
trim
方法称为strip
:对于前导和尾随空格:
否则,正则表达式起作用:
您还可以使用非常简单的基本函数:str.replace(),使用空格和制表符:
简单易行 .
还没有人发布这些正则表达式解决方案 .
匹配:
搜索(您必须以不同方式处理“仅空格”输入大小写):
如果使用
re.sub
,则可能会删除内部空格,这可能是不合需要的 .空白包括 space, tabs and CRLF . 所以我们可以使用的优雅和 one-liner 字符串函数是 translate .
' hello apple'.translate(None, ' \n\t\r')
OR 如果你想要彻底
输出:please_remove_all_whitespaces
这将删除所有不需要的空格和换行符 . 希望这有帮助
这将导致:
' a b \n c ' 将更改为 'a b c'
尝试翻译
如果使用Python 3:在print语句中,请使用sep =“”结束 . 这将分离出所有空间 .
例:
This will print: 我喜欢土 beans .
Instead of: 我喜欢土 beans .
在你的情况下,因为你试图乘坐\ t,所以做sep =“\ t”
一般来说,我使用以下方法:
注意:这仅用于删除“\ n”,“\ r”和“\ t” . 它不会删除多余的空格 .
用于从字符串中间删除空格
输出:ATGCGACACGATCGACC