Concatenate 2 strings from 2 different lines (From text file) - Using linecache

133 Views Asked by At

I am trying to concatenate 2 string from two different lines using linecache but when i try, the output is always on 2 lines not on 1 line.

Text in the file:

hello

world

Code:

import linecache
import easygui

a=linecache.getline("textfile.txt",1)
b=linecache.getline("textfile.txt",2)

easygui.msgbox (a+b)

Result:

The result(message) is: hello world on two lines(on the first line is hello on the second is world)

that is not what i want, i want this: hello world on a single line

Any help would be appreciated! :-)

P.S. Sorry for my english!

2

There are 2 best solutions below

0
Rushy Panchal On BEST ANSWER

You want to strip the trailing newlines:

a = linecache.getline("textfile.txt",1).rstrip("\n")
b = linecache.getline("textfile.txt",2).rstrip("\n")

str.rstrip("\n") strips newlines from the right side of the string.

0
Andomar On

Remove the newline from the first string:

easygui.msgbox a.rstrip("\n\r") + b