2015-11-05 50 views
0

我在Python中将控制台输出存储在字符串中。如何比较Python中的字符串中的2行

它看起来像:

output ="Status of xyz 
     Process is running 

     Status of abc 
     Process is stopped" 

我想每行的最后一个字,并与下一行的最后一个字比较。 我如何在Python中做到这一点?

+0

欢迎使用Stackoverflow。到目前为止你有没有尝试过任何东西 – Kasramvd

+0

什么样的比较?看看他们是否平等? – dstudeba

+1

看看split()函数。它会帮助你将单词分成列表。 – dmitri

回答

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

Windows上的''.split('\ n')''方法可能会在行尾留下额外的'''\ r'''字符。 ''.splitlines()''方法是跨平台的。 –

+0

循环遍历一个''range''然后建立索引很容易出现错误。 Pythonic的方法是使用python的内置迭代器之一。 –

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