首页 > 解决方案 > 从Python中的字符串中删除最后一行

问题描述

我有一个这样的字符串:

line1
line2
line3
line_i_want_to_remove

我想删除最后一个接收这样的东西:

line1
line2
line3

我知道如何删除第一行,我使用这个:

string = string.split("\n",3)[3]

但是,我怎样才能删除最后一个?

标签: pythonstring

解决方案


简短的回答:

string = '\n'.join(string.split('\n')[:-1])

更长的答案:

# split text on newlines, gives list of strings, one entry for each line
all_lines = string.split('\n')

# take a slice of this list, from beginning up until the next to last one
all_lines_except_last = all_lines[:-1]  # this is the same as all_lines[0:len(all_lines)-1]

# then join the remaining lines back together with newlines into a single string again
string = '\n'.join(all_lines_except_last)

切片:https ://docs.python.org/3/glossary.html#term-slice

有关切片用法的更多示例:https ://docs.python.org/3/whatsnew/2.3.html#extended-slices


推荐阅读