【问题标题】:Is there a simple way to start splitting a string from a certain point?有没有一种简单的方法可以从某个点开始拆分字符串?
【发布时间】:2021-01-21 18:39:55
【问题描述】:

假设我有这个字符串'This is an example hello'

如果拆分会变成['This', 'is', 'an', 'example', 'hello']

如果我只想取最后三个单词并将它们放在一个列表中,得到['an', 'example', 'hello'] 有没有一种简单的方法可以做到这一点?

一个想法当然是拆分整个句子,然后只删除第一个元素,但我想知道是否还有其他方法可以直接获得相同的结果。提前谢谢你。

PS:这是我在这里提出的第一个问题,如果不完美,我很抱歉,请指出可能存在的问题,以便我下次改进! :)

【问题讨论】:

  • 你可以使用rsplit()
  • rsplit(limit=3)
  • last_items = st.split()[-3:]
  • 查找splitting 查找您的第一个问题,查找slicing 查找第二个问题:)

标签: python string line


【解决方案1】:

试试这个

string = 'This is an example hello'

split = string.split()[-3:]

因为我们知道拆分字符串返回一个列表,所以我们可以使用[-3:]获取列表的最后3个元素。

【讨论】:

    【解决方案2】:

    使用 str.rsplit 及其可选的 maxsplit 参数。并使用* 运算符将其打包成list

    >>> string = 'This is an example hello'
    >>> first_part, *last_three = string.rsplit(sep=' ', maxsplit=3)
    
    >>> first_part
    'This is'
    
    >>> last_three
    ['an', 'example', 'hello']
    

    【讨论】:

      猜你喜欢
      • 2013-02-21
      • 2017-03-13
      • 2020-02-16
      • 2010-12-05
      • 2020-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多