Tahir Sanwarwala
Tahir Sanwarwala

Reputation: 21

Print without starting a newline

I know this question has been asked before a lot. But for some reason, I can't seem to get it to work in my code.

I'm new to coding and just trying out a few things for a start.

string1 = 'Coding'
with open('Example.txt', 'r') as f1:
    with open('Output.txt', 'w') as f2:
        for line in f1:
            if line.startswith(string1):
                print(next(f1), end="", file=f2)
                print(next(f1), file=f2)

INPUT

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
Coding
Hello
World
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

OUTPUT

Hello
World

I want it to come as "Hello World". In the same line. Even the end='' command doesn't seem to work here.

Upvotes: 2

Views: 38

Answers (1)

atru
atru

Reputation: 4744

Your code was doing what you intended it to do. The problem was that your input file had newline characters at the end of each line. This is why the text in the output still appeared split.

To fix, you can remove the newline characters using strip(),

string1 = 'Coding'
with open('Example.txt', 'r') as f1:
    with open('Output.txt', 'w') as f2:
        for line in f1:
            if line.startswith(string1):
                print(next(f1).strip(), end=" ", file=f2)
                print(next(f1).strip(), file=f2)

Notice that the first print statement now ends with a space - otherwise the output would end up HelloWorld.

Upvotes: 1

Related Questions