如果字符串是换行符,我如何删除它的最后一个字符?
"abc\n" --> "abc"
如果字符串是换行符,我如何删除它的最后一个字符?
"abc\n" --> "abc"
当前回答
尝试rstrip()方法(参见文档Python 2和Python 3)
>>> 'test string\n'.rstrip()
'test string'
Python的rstrip()方法在默认情况下去除了所有类型的尾随空格,而不是像Perl使用chomp那样只去除一行换行符。
>>> 'test string \n \r\n\n\r \n\n'.rstrip()
'test string'
要仅删除换行符,请执行以下操作:
>>> 'test string \n \r\n\n\r \n\n'.rstrip('\n')
'test string \n \r\n\n\r '
除了rstrip(),还有strip()和lstrip()方法。下面是其中三个示例:
>>> s = " \n\r\n \n abc def \n\r\n \n "
>>> s.strip()
'abc def'
>>> s.lstrip()
'abc def \n\r\n \n '
>>> s.rstrip()
' \n\r\n \n abc def'
其他回答
您可以使用line=line.rstrip('\n')。这将从字符串末尾删除所有换行符,而不仅仅是一行。
对于perl的chomp,似乎没有完美的模拟。特别是,rstrip不能处理像\r\n这样的多字符换行符。然而,分裂线确实如这里所指出的那样。根据我对另一个问题的回答,您可以组合连接和拆分线来删除/替换字符串中的所有换行符:
''.join(s.splitlines())
下面只删除了一个尾随换行符(我相信chomp会这样做)。将True作为keeponds参数传递给拆分线将保留分隔符。然后,再次调用拆分线以删除最后一行上的分隔符:
def chomp(s):
if len(s):
lines = s.splitlines(True)
last = lines.pop()
return ''.join(lines + last.splitlines())
else:
return ''
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 = s.rstrip()
将删除字符串s末尾的所有换行符。需要赋值,因为rstrip返回一个新字符串,而不是修改原始字符串。
"line 1\nline 2\r\n...".replace('\n', '').replace('\r', '')
>>> 'line 1line 2...'
或者你可以用regexp变得更古怪