Print one word from a string in python

How can I print only specific words from a string in python? let's say I want to print only the third word (this number) and 10th place

while the length of the text may vary each time

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

thank.

+3
source share
6 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])
+7
source

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

In this case, you want to combine enough so that you have confidence that you correspond to the right thing, but not so much, if the result changes a little, your program will go wrong.

Regular expressions work well in this case, for example

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

mystring = " 15 32000"

print mystring.split( ") [2] #prints 3-

print mystring.split(" ") [9] #prints 10-

+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])

, 0, *

+2

str.split().

Alternatively, if you are looking for certain things, you can try regular expressions; that could handle the replacement of filler words. But if all you care about is the position of the word in the line, then splitting and printing certain elements of the resulting list will be the easiest.

0
source

How about this:

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)

Result:

 15 
 32000
0
source

Source: https://habr.com/ru/post/1745581/


All Articles