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

时间:2015-11-05 07:17:18

标签: python compare

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

看起来像:

output ="Status of xyz  
         Process is running

         Status of abc 
         Process is stopped"

我想得到每一行的最后一个字,并与下一行的最后一个字进行比较。 我怎么能用Python做到这一点?。

2 个答案:

答案 0 :(得分:2)

首先,您需要将字符串分隔为行列表:

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

答案 1 :(得分:0)

这是数据

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