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.
mystring = "You have 15 new messages and the size is 32000"
parts = mystring.split(' ')
message_count = int(parts[2])
message_size = int(parts[9])
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With