I have the console output stored in a string in Python.
It looks like:
output ="Status of xyz
Process is running
Status of abc
Process is stopped"
I want to get last word of each line and compare with last word of next line. How can I do this in Python?.
First you need to separate the string into a list of lines:
lines = output.split('\n') #splits into lines
Then you need to loop over the lines and split the line into words
#we go through all lines except the last, to check the line with the next
for lineIndex in range(len(lines)-1):
# split line to words
WordsLine1 = lines[lineIndex].split()
WordsLine2 = lines[lineIndex+1].split() # split next line to words
#now check if the last word of the line is equal to the last word of the other line.
if ( WordsLine1[-1] == WordLine2[-1]):
#equal do stuff..
Here's the data
data = """\
Status of xyz Process is running
Status of abc Process is stopped
"""
Split into lines in a cross-platform manner:
lines = data.splitlines()
Loop over the lines pairwise, so you have the current line and the previous line at the same time (using zip
):
for previous, current in zip(lines, lines[1:]):
lastword = previous.split()[-1]
if lastword == current.split()[-1]:
print('Both lines end with the same word: {word}'.format(word=lastword))
Alternatively, if you don't like how zip
looks, we can loop over the lines pairwise by repeatedly setting a variable to store the last line:
last = None
for line in lines:
if last is not None and line.split()[-1] == last.split()[-1]:
print('both lines have the same last word')
last = line
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.