如果字符串是换行符,我如何删除它的最后一个字符?
"abc\n" --> "abc"
如果字符串是换行符,我如何删除它的最后一个字符?
"abc\n" --> "abc"
当前回答
我发现,通过迭代器获取压缩行很方便,与从文件对象获取未压缩行的方式类似。您可以使用以下代码执行此操作:
def chomped_lines(it):
return map(operator.methodcaller('rstrip', '\r\n'), it)
示例用法:
with open("file.txt") as infile:
for line in chomped_lines(infile):
process(line)
其他回答
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)
我可能会用这样的方法:
import os
s = s.rstrip(os.linesep)
我认为rstrip(“\n”)的问题是您可能需要确保行分隔符是可移植的。(一些过时的系统据说使用“\r\n”)。另一个陷阱是rstrip将去掉重复的空格。希望os.lineep包含正确的字符。以上这些对我很有用。
>>> ' spacious '.rstrip()
' spacious'
>>> "AABAA".rstrip("A")
'AAB'
>>> "ABBA".rstrip("AB") # both AB and BA are stripped
''
>>> "ABCABBA".rstrip("AB")
'ABC'
您可以使用line=line.rstrip('\n')。这将从字符串末尾删除所有换行符,而不仅仅是一行。
小心使用“foo”.rstrip(os.lineep):这只会在执行Python的平台上压缩换行符。例如,假设您在Linux下敲击Windows文件的行:
$ python
Python 2.7.1 (r271:86832, Mar 18 2011, 09:09:48)
[GCC 4.5.0 20100604 [gcc-4_5-branch revision 160292]] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os, sys
>>> sys.platform
'linux2'
>>> "foo\r\n".rstrip(os.linesep)
'foo\r'
>>>
请改用“foo”.rstrip(“\r\n”),如Mike所述。