使用Python3删除新行

时间:2018-10-11 14:09:37

标签: python python-3.x

如何使用python删除垂直制表符和退格键(字符ASCII代码013 010)?我尝试使用以下代码,但无法正常工作。

text = re.sub('\n', ' ', text) // after execute, removed all text except for last line
text = text.replace('\n',' ') // after execute, removed all text except for last line
text = text.rstrip() 
text = text.lstrip()
text = text.strip()

这是原始字符串:

Only certified persons are allowed to use the research equipment and facilities
 at NSL. There are several things users need to do before they are given access
 to the labs. All new users must complete steps 1-3 (and step 4 for those planning 
 to perform chemical operations at NSL.)


 Every user must complete the user form and submit it to nanosystemslaboratory@osu.edu. 
 Internal users (OSU users) must fill the erequest number under the chartfield section of the user form. 
 Failure to provide an erequest number for the associated chartfield may delay processing of the user form.

所需的输出是单行文本,例如:line1 line2 line3

Only certified persons ... Every user must complete the user ...

3 个答案:

答案 0 :(得分:0)

我认为您想尝试的是line.strip()。它可以同时使用空格和制表符,并保留它们之间的空格。

line = '   this is my example          '
line.strip() == 'this is my example'

答案 1 :(得分:0)

解决方案也是'\ r',并且ascii代码也等同于013。谢谢大家以下语句对于删除退格字符很有用。

text = text.replace('\r',' ')

答案 2 :(得分:-1)

text = text.replace('\n', '')
text = text.replace(' ', '')

如果我了解您的问题,那么此行足以解决问题。作为总结,我先删除了换行符,然后再删除了空格。