繁体   English   中英

如何在Python中比较字符串中的2行

[英]How do I compare 2 lines in a string in Python

我将控制台输出存储在Python中的字符串中。

看起来像:

output ="Status of xyz  
         Process is running

         Status of abc 
         Process is stopped"

我想获得每行的最后一个单词,并与下一行的最后一个单词进行比较。 如何在Python中执行此操作?

首先,您需要将字符串分成几行:

lines = output.split('\n')  #splits into lines

然后,您需要遍历行并将行拆分为单词

#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..

这是数据

data = """\
Status of xyz Process is running
Status of abc Process is stopped
"""    

以跨平台方式分成几行:

lines = data.splitlines()

成对循环遍历两行,因此您可以同时拥有当前行和上一行(使用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))

另外,如果您不喜欢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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM