Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print one word from a string in python

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 may be different each time

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

thanks.

like image 425
Shai Avatar asked Dec 02 '22 05:12

Shai


2 Answers

mystring = "You have 15 new messages and the size is 32000"
parts = mystring.split(' ')
message_count = int(parts[2])
message_size = int(parts[9])
like image 128
ThiefMaster Avatar answered Dec 06 '22 09:12

ThiefMaster


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
like image 44
Nick Craig-Wood Avatar answered Dec 06 '22 11:12

Nick Craig-Wood