如果字符串是换行符,我如何删除它的最后一个字符?
"abc\n" --> "abc"
如果字符串是换行符,我如何删除它的最后一个字符?
"abc\n" --> "abc"
当前回答
s = '''Hello World \t\n\r\tHi There'''
# import the module string
import string
# use the method translate to convert
s.translate({ord(c): None for c in string.whitespace}
>>'HelloWorldHiThere'
使用正则表达式
s = ''' Hello World
\t\n\r\tHi '''
print(re.sub(r"\s+", "", s), sep='') # \s matches all white spaces
>HelloWorldHi
替换\n,\t,\r
s.replace('\n', '').replace('\t','').replace('\r','')
>' Hello World Hi '
使用正则表达式
s = '''Hello World \t\n\r\tHi There'''
regex = re.compile(r'[\n\r\t]')
regex.sub("", s)
>'Hello World Hi There'
使用Join
s = '''Hello World \t\n\r\tHi There'''
' '.join(s.split())
>'Hello World Hi There'
其他回答
s = '''Hello World \t\n\r\tHi There'''
# import the module string
import string
# use the method translate to convert
s.translate({ord(c): None for c in string.whitespace}
>>'HelloWorldHiThere'
使用正则表达式
s = ''' Hello World
\t\n\r\tHi '''
print(re.sub(r"\s+", "", s), sep='') # \s matches all white spaces
>HelloWorldHi
替换\n,\t,\r
s.replace('\n', '').replace('\t','').replace('\r','')
>' Hello World Hi '
使用正则表达式
s = '''Hello World \t\n\r\tHi There'''
regex = re.compile(r'[\n\r\t]')
regex.sub("", s)
>'Hello World Hi There'
使用Join
s = '''Hello World \t\n\r\tHi There'''
' '.join(s.split())
>'Hello World Hi There'
包罗万象:
line = line.rstrip('\r|\n')
在很多层面上,rstrip做的事情与chomp不同。阅读http://perldoc.perl.org/functions/chomp.html看到chomp确实非常复杂。
然而,我的主要观点是chomp最多删除1行结尾,而rstrip将删除尽可能多的结尾。
在这里,您可以看到rstrip删除了所有换行符:
>>> 'foo\n\n'.rstrip(os.linesep)
'foo'
使用re.sub可以更接近典型的Perl chomp用法,如下所示:
>>> re.sub(os.linesep + r'\Z','','foo\n\n')
'foo\n'
Python文档中的一个示例简单地使用了line.strip()。
Perl的chomp函数仅在字符串末尾有一个换行符序列时才将其删除。
以下是我计划在Python中实现这一点的方法,如果process在概念上是我需要的函数,以便对该文件中的每一行执行一些有用的操作:
import os
sep_pos = -len(os.linesep)
with open("file.txt") as f:
for line in f:
if line[sep_pos:] == os.linesep:
line = line[:sep_pos]
process(line)
我不使用Python编程,但我在Python.org上遇到了一个常见问题解答,建议使用Python 2.2或更高版本的S.rstrip(“\r\n”)。