Print one word from a string in python

前端 未结 6 949
既然无缘
既然无缘 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:40

    It looks like you are matching something from program output or a log file.

    In this case you want to match enough so you have confidence you are matching the right thing, but not so much that if the output changes a little bit your program goes wrong.

    Regular expressions work well in this case, eg

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

提交回复
热议问题