按行拆分字符串并返回列表:
"This\nis a\nmultiline\nstring.\n"
def split_lines(s,mode=1):
if mode == 1:
return s.split("\n")
elif mode == 2:
return s.splitlines()
elif mode == 3:
return s.splitlines(keepends = True)
print('1.split:')
print(split_lines("This\nis a\nmultiline\nstring.\n"))
print('2.splitlines:')
print(split_lines("This\nis a\nmultiline\nstring.\n",mode=2))
print('3.splitlines(keepends version):')
print(split_lines("This\nis a\nmultiline\nstring.\n",mode=3))
比较了一下split和splitlines的区别,对于最后一行的换行符,split会留空,而splitlines才会完全消去换行符,其中的keepends关键字参数,个人理解相当于转义,使\n不表示换行的特殊意义