[英]How do I compare 2 lines in a string in Python
I have the console output stored in a string in Python. 我将控制台输出存储在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?.
如何在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
): 成对循环遍历两行,因此您可以同时拥有当前行和上一行(使用
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: 另外,如果您不喜欢
zip
外观,我们可以通过重复设置变量来存储最后一行来成对循环:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.