0

started a few days ago with python coding, atm doing some work on my discord bot.

my problem atm is that i cannot join 2 lines out of a .txt file in my print output.

the code itself works exactly as it should.

my output atm:

Spieler Online:
864

expected output:

Spieler Online:864

the method i'm actually using is

with open('test.txt') as fp:
lines=fp.readlines()
print (lines[148] +lines[150])

tried so much things from google/stackoverflow but nothing gets me the expected output.

thanks a bunch for every idea.

TheEagle
  • 5,808
  • 3
  • 11
  • 39
0x9
  • 11
  • 2
  • You have `\n` on the end of every line since `.readlines()` does not strip that off. – dawg Mar 27 '21 at 16:52

5 Answers5

1

The problem is the lines end with '\n' (newline character), so when printed you also print the '\n' which gets translated into printing two lines.

with open('test.txt') as fp:
    lines = fp.readlines()
print(lines[148].strip('\n') + lines[150].strip('\n'))
miquelvir
  • 1,748
  • 1
  • 7
  • 21
0

You can use Join() method to merge two lines.

taha yab
  • 41
  • 2
  • 6
0

Because you are trying to print 2 different lines, both of the lines have '\n' at the end. In your print statement you are essentially saying print("Spieler Online:\n864\n"). If you want to print both of them on the same line you will have to strip the '\n' from the first line. To do this you can for example use your_string.rstrip("\n")

Seppeke
  • 143
  • 7
0

In the print statement, you can use the argument 'sep' to your advantage.

Just instead of:

with open('test.txt') as fp:
    lines=fp.readlines()
    print (lines[148] +lines[150])

Use:

with open('test.txt') as fp:
    lines=fp.readlines()
    print (lines[148],lines[150],sep=' ')

The sep argument helps to change the separation between the two strings from the default separation, i.e., \n to whitespace (' ').

Shuvam Paul
  • 120
  • 4
0

try

with open('test.txt') as fp:
    lines=fp.readlines()
    print (lines[148].split('\n')[1]+' '+lines[150].split('\n')[0])

Harsh
  • 151
  • 1
  • 2