Search code examples
pythonlinecache

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


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!


Solution

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