Home > Net >  how to add string in previous line to the end of next line in python
how to add string in previous line to the end of next line in python

Time:07-15

I want to add string startswith "AA" to the end of next line like this (that have many lines in text)

input:

AA

1 A B C 

2 D E F 

AA

3 G H I 

output:

1 A B C AA

2 D E F 

3 G H I AA

CodePudding user response:

you need to keep two lists, a temporary one to keep all your string that start with "AA" and other for the output and fill them accordingly

>>> text="""AA

1 A B C

2 D E F

AA

3 G H I"""

>>> output=[]
>>> temp=[]
>>> for line in text.splitlines():
        line = line.strip() #remove trailing while spaces
        if not line:
            continue #ignore empty lines
        if line.startswith("AA"):
            temp.append(line)
        else:
            if temp: #concatenate our temp list if there anything there
                line  = " "   " ".join(temp)
                temp.clear() 
            output.append(line)
    
            
>>> print("\n".join(output))
1 A B C AA
2 D E F
3 G H I AA
>>> 

CodePudding user response:

import sys
checker="AA" 
raw=sys.stdin.readlines() # paste test from clipboard and ctrl   z input
lines=list(map(str.strip,raw))
result=[]
for i in range(0,len(lines)-1):
    if lines[i] == checker:
        result.append(lines[i 1] lines[i])
    else:
        pass
result_str='\n'.join(result)
print(result_str)

I hope it wiil work for you.

  • Related