Print one word from a string in python

前端 未结 6 957
既然无缘
既然无缘 2021-01-14 01:21

How can i print only certain words from a string in python ? lets say i want to print only the 3rd word (which is a number) and the 10th one

while the text length ma

6条回答
  •  没有蜡笔的小新
    2021-01-14 01:37

    This function does the trick:

    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']
    

    The alternative indicated by Ignacio is very clean:

    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() ...

    Return a callable object that fetches the given item(s) from its operand.

    After, f = itemgetter(2), the call f(r) returns r[2].

    After, g = itemgetter(2,5,3), the call g(r) returns (r[2], r[5], r[3])

    Note that now positions in position should be counted from 0 to allow using directly the *position argument

提交回复
热议问题