如果字符串是换行符,我如何删除它的最后一个字符?

"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'

其他回答

我不使用Python编程,但我在Python.org上遇到了一个常见问题解答,建议使用Python 2.2或更高版本的S.rstrip(“\r\n”)。

"line 1\nline 2\r\n...".replace('\n', '').replace('\r', '')
>>> 'line 1line 2...'

或者你可以用regexp变得更古怪

只需使用:

line = line.rstrip("\n")

or

line = line.strip("\n")

你不需要这些复杂的东西

特殊情况的解决方案:

如果换行符是最后一个字符(大多数文件输入都是这样),那么对于集合中的任何元素,都可以按如下方式进行索引:

foobar= foobar[:-1]

剪切换行符。

您可以使用line=line.rstrip('\n')。这将从字符串末尾删除所有换行符,而不仅仅是一行。