python - 如何按字符串拆分列表

标签 python string list split

我有几个大的字符串列表。我需要将所有这些列表拆分为两个列表,以便只保留第二个列表。例如:

lst = ['This is a list', 'of strings', 'blahblahblah', 'split_here', 'something else', 'we like cake', 'aardvarks']

我只想抓取 'split_here' 之后的字符串,这样新列表就是这样的:

new_lst = ['something else', 'we like cake', 'aardvarks']

我试过这个:

new_list = str(lst).split('split_here')[1]

但是新输出有一堆转义字符(“\”符号)。我尝试将它们替换为:

.replace('\\', '')

但这也没有用。

我认为必须有一种简单的方法来执行此操作,而我却缺少这种方法。

最佳答案

您正在寻找列表操作,而不是字符串操作。我们只需要找到分隔符字符串出现的位置,然后从下一个元素开始切片,就像这样:

lst = ['This is a list', 'of strings', 'blahblahblah', 'split_here', 'something else', 'we like cake', 'aardvarks']
new_list = lst[lst.index('split_here')+1:]

以上假定列表中存在分隔符字符串,否则我们将得到一个ValueError。结果符合预期:

new_list
=> ['something else', 'we like cake', 'aardvarks']

关于python - 如何按字符串拆分列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54502131/

相关文章:

python - 使用 lxml 的 etree 创建文档类型

python - 什么时候使用 super(Baseclass, self).__init__

python - Argparse: "-p"或 "-p=value"但不是 "-p value"

c++ - std::string 在 std::cin 的 4095 个字符后被截断

c++ - 在 C++ 中使用 Arduino 上的数组

python - 如何在 Flask-Jinja Python 中使用列表中的列表

python - 如何在没有数据或彩色图像的情况下获得清晰的图像。 opencv python

c# - 如何获取此字符串中标签的 href 属性?

python - 优化两个列表之间的比较,给出不同的索引

python - 无法在 Python 中随机播放列表