【问题标题】:Print one word from a string in python从python中的字符串中打印一个单词
【发布时间】:2010-05-15 18:02:03
【问题描述】:

如何在 python 中只打印字符串中的某些单词? 假设我只想打印第三个单词(这是一个数字)和第十个

虽然每次文字长度可能不同

mystring = "You have 15 new messages and the size is 32000"

谢谢。

【问题讨论】:

  • 下面的答案似乎对你有用。请点击该答案的票数下方的复选框;这样您的问题就会被标记为“已回答”。
  • 请开始回答问题。这就像说“谢谢”。

标签: python string split printing


【解决方案1】:
mystring = "You have 15 new messages and the size is 32000"
parts = mystring.split(' ')
message_count = int(parts[2])
message_size = int(parts[9])

【讨论】:

    【解决方案2】:

    看起来您正在匹配程序输出或日志文件中的某些内容。

    在这种情况下,您希望匹配得足够多,这样您就有信心匹配正确的东西,但不要太多,以至于如果输出稍有变化,您的程序就会出错。

    正则表达式在这种情况下效果很好,例如

    >>> import re
    >>> mystring = "You have 15 new messages and the size is 32000"
    >>> match = re.search(r"(\d+).*?messages.*?size.*?(\d+)", mystring)
    >>> if not match: print "log line didn't match"
    ... 
    >>> messages, size = map(int, match.groups())
    >>> messages
    15
    >>> size
    32000
    

    【讨论】:

      【解决方案3】:
      mystring = "You have 15 new messages and the size is 32000"
       
      print mystring.split(" ")[2]  #Prints the 3rd word
      
      print mystring.split(" ")[9] #Prints the 10th word
      

      【讨论】:

        【解决方案4】:

        这个函数可以解决问题:

        def giveme(s, words=()):
            lista = s.split()    
            return [lista[item-1] for item in words]   
        
        mystring = "You have 15 new messages and the size is 32000"
        position = (3, 10)
        print giveme(mystring, position)
        
        it prints -> ['15', '32000']
        

        Ignacio 指出的替代方案非常干净:

        import operator
        
        mystring = "You have 15 new messages and the size is 32000"
        position = (2, 9)
        
        lista = mystring.split()
        f = operator.itemgetter(*position)
        print f(lista)
        
        it prints -> ['15', '32000']
        

        operator.itemgetter() ...

        返回一个获取的可调用对象 来自其操作数的给定项目。

        之后,f = itemgetter(2),调用f(r) 返回 r[2]。

        之后,g = itemgetter(2,5,3),调用g(r) 返回 (r[2], r[5], r[3])

        请注意,现在 position 中的位置应从 0 开始计数,以允许直接使用 *position 参数

        【讨论】:

        • @Ignacio:谢谢,我不知道。太棒了!
        【解决方案5】:

        看看str.split()

        或者,如果您正在寻找某些东西,您可以尝试使用正则表达式;甚至可以应对填充词的变化。但是,如果您只关心字符串中的单词位置,那么拆分并打印出结果列表中的某些元素将是最直接的。

        【讨论】:

          【解决方案6】:

          这个怎么样:

          import re
          
          tst_str = "You have 15 new messages and the size is 32000"
          items = re.findall(r" *\d+ *",tst_str)
          for item in items:
              print(item)
          

          结果:

           15 
           32000
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-09-03
            • 1970-01-01
            • 2017-11-23
            • 1970-01-01
            • 1970-01-01
            • 2020-11-06
            相关资源
            最近更新 更多