How to join second line to end of first line in python? -
i tried read lines below:
a:129 tyr -p- 9 - - - 10xr,4xg,3xd,3xk,2xp,2xv,2xy,1xe,1xi,1xl,1xm,1xn,1 xq,1xt a:181 ser -p- 8 - - - 9xr,9xs,8xg,4xt,3xd,3xl,3xq,3xv,2xk,2xm,1xa,1xf,1x h,1xy a:50 --- 9 - - - 17xl,9xa,4xk,3xi,3xr,3xv,2xn,2xs,1xc,1xe,1xh,1xq,1 xt where each lines continuation of odd lines split "\n\s\s\s\s\s\s\s\s\s\s\s\s\s\s\s\s\s\s\s\s\s\s\s\s\s\s\s\s\s\s\s\s\s\s\s\s\s\s\s\s\s\s\s\s\s\s\s\s\s\s\s\s\s\s\s\s\s\s\s\s\s\s\s\s\s\s\s" so want replace '\n\s(n)' '' , join end of odd lines .
for example:
a:181 ser -p- 8 - - - 9xr,9xs,8xg,4xt,3xd,3xl,3xq,3xv,2xk,2xm,1xa,1xf,1x h,1xy to
a:181 ser -p- 8 - - - 9xr,9xs,8xg,4xt,3xd,3xl,3xq,3xv,2xk,2xm,1xa,1xf,1xh,1xy code:
import os import sys import re lines=["a:129 tyr -p- 9 - - - 10xr,4xg,3xd,3xk,2xp,2xv,2xy,1xe,1xi,1xl,1xm,1xn,1"," xq,1xt","a:181 ser -p- 8 - - - 9xr,9xs,8xg,4xt,3xd,3xl,3xq,3xv,2xk,2xm,1xa,1xf,1x"," h,1xy","a:50 --- 9 - - - 17xl,9xa,4xk,3xi,3xr,3xv,2xn,2xs,1xc,1xe,1xh,1xq,1"," xt"] in lines: print i.replace(" ","") here,i replaced spaces empty space didnt how join replaced lines end of odd lines.
so 1 me same.
thanking in advance.
hi guys , first of many more kind replies. tried ways followed 1 works correct:
wild= open("input.txt", 'r') merged = [] line in wild: if line.startswith(" "): merged[-1] += line.strip() else: merged.append(line.replace("\n","")) output:
a:129 tyr -p- 9 - - - 10xr,4xg,3xd,3xk,2xp,2xv,2xy,1xe,1xi,1xl,1xm,1xn,1xq,1xt a:181 ser -p- 8 - - - 9xr,9xs,8xg,4xt,3xd,3xl,3xq,3xv,2xk,2xm,1xa,1xf,1xh,1xy a:50 --- 9 - - - 17xl,9xa,4xk,3xi,3xr,3xv,2xn,2xs,1xc,1xe,1xh,1xq,1xt
read entire file single string, replace entire whitespace single tab:
filepointer = open("input.txt") text = filepointer.read() text = re.sub(r"\n\s{20,}", "\t", text) this matches , removes sequences of newline followed 20 or more spaces, replacing them tab. (that way don't have count precise number of spaces, , program still works if lines different). if don't want tab between joined lines, use space (" ") instead of "\t".
and if must have result list of lines, split text afterwards:
merged = text.splitlines()
Comments
Post a Comment