【问题标题】:How to extract the first and final words from a string?如何从字符串中提取第一个和最后一个单词?
【发布时间】:2017-05-04 19:56:34
【问题描述】:

我在学校需要做的事情上有一个小问题......

我的任务是从用户那里获取原始输入字符串 (text = raw_input()) 我需要打印该字符串的第一个和最后一个单词。

有人可以帮我吗?我整天都在寻找答案......

【问题讨论】:

  • 最后一个词是指最后一个词吗?请提及示例示例
  • "Hello World!" 中的最后一个单词是字符串"World!" 还是单词"World"

标签: python string split extract


【解决方案1】:

你会这样做:

print text.split()[0], text.split()[-1]

【讨论】:

    【解决方案2】:

    您必须首先使用str.split 将字符串转换为单词的list,然后您可以像这样访问它:

    >>> my_str = "Hello SO user, How are you"
    >>> word_list = my_str.split()  # list of words
    
    # first word  v              v last word
    >>> word_list[0], word_list[-1]
    ('Hello', 'you')
    

    从 Python 3.x,您可以简单地这样做:

    >>> first, *middle, last = my_str.split()
    

    【讨论】:

    • 谢谢,我很感激 :) 谢谢你,我也知道了 split() 的作用
    【解决方案3】:

    假设x 是您的输入。那么你可以这样做:

     x.partition(' ')[0]
     x.partition(' ')[-1]
    

    【讨论】:

    • partition 只会砍掉x 一次(所以,你会得到第一个单词,然后是句子的其余部分,而不是最后一个单词)。
    • @wildwilhelm:这个答案有可能是 OP 所期望的,因为 final words 的定义尚不清楚。值得怀疑的是,答案不应该被否决
    • 是的,我同意问题措辞模棱两可。否决票已撤回。
    【解决方案4】:

    有人可能会说,使用正则表达式的答案永远不会太多(在这种情况下,这看起来是最糟糕的解决方案..):

    >>> import re
    >>> string = "Hello SO user, How are you"
    >>> matches = re.findall(r'^\w+|\w+$', string)
    >>> print(matches)
    ['Hello', 'you']
    

    【讨论】:

      【解决方案5】:

      如果您使用的是 Python 3,则可以这样做:

      text = input()
      first, *middle, last = text.split()
      print(first, last)
      

      除了第一个和最后一个单词之外的所有单词都将进入变量middle

      【讨论】:

      • 酷,我第一次看到这个功能。
      • 不错。如果还需要中间词,这是非常干净的方法
      • 这很好,尽管它在 1 个单词的句子的边缘情况下失败了(可以说应该将 1 个单词作为第一个单词和最后一个单词返回)。
      • @JohnColeman,在这种情况下,它与ValueError: not enough values to unpack 出错,恕我直言,这是对“当单词没有空格时无法在空格处拆分单词”的合理解释。
      【解决方案6】:

      只需将您的字符串传递给以下函数

      def first_and_final(str):
          res = str.split(' ')
          fir = res[0]
          fin = res[len(res)-1]
          return([fir, fin])
      

      用法

      first_and_final('This is a sentence with a first and final word.')
      

      结果

      ['This', 'word.']
      

      【讨论】:

        【解决方案7】:

        您可以使用 .split 和 pop 从字符串中检索单词。 使用“0”获取第一个单词,使用“-1”获取最后一个单词。

        string = str(input())
        print(string.split().pop(0))
        print(string.split().pop(-1))
        

        【讨论】:

          猜你喜欢
          • 2021-12-27
          • 1970-01-01
          • 1970-01-01
          • 2011-04-02
          • 2022-12-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多