python - 从Python中的字符串中删除最后一行
问题描述
我有一个这样的字符串:
line1
line2
line3
line_i_want_to_remove
我想删除最后一个接收这样的东西:
line1
line2
line3
我知道如何删除第一行,我使用这个:
string = string.split("\n",3)[3]
但是,我怎样才能删除最后一个?
解决方案
简短的回答:
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
推荐阅读
- linux - 如果满足条件,在重新启动后自动启动 Linux 服务时出错:“条件中的路径不是绝对的,忽略”
- ios - 缓存 Firebase 视频网址时,URLSession 移动缓慢
- javascript - 从另一个文件客户端导入函数
- c - 从链表中删除元素的函数的时间复杂度是多少?
- java - Spring batch - JdbcPagingItemReader, SQLServerException: 列名 XYZ 无效
- graph - TeX 中的条形图格式不正确
- python-2.7 - 无法使用 Pycharm 安装 arcpy 模块
- amazon-web-services - 如何通过 Boto3 API 在 AWS 中添加弹性 IP 名称?
- android - 尝试初始化 Activity Android 时,Robolectric 出现类型不匹配错误
- javascript - React 中由 ref jumpy 链接的滚动框/条(尤其是移动端)