home changes contents help options

055:行末の改行を取り除く

rstripメソッドを用いると、右端にある空白文字が取りのぞかれます。

 >>> str_a="banana\n"
 >>> str_b="apple\r\n"
 >>> str_a.rstrip()
 'banana'
 >>> str_b.rstrip()
 'apple'
 取り除く文字を指定することもできます。
 >>> str_b.rstrip("\n")
 'apple\r'

こんな方法もあります。

 if line.endswith("¥r¥n"): line = line[:-2]
 if line.endswith("¥n"): line = line[:-1]