Home > OS >  Combine variable text in iterating over a sequence from file in python ('for' loop) withou
Combine variable text in iterating over a sequence from file in python ('for' loop) withou

Time:08-31

I write a little more clearly. Here, I want each line to stick together twice. normally from

a = "Hello"
b = "World"
print(a   b)

out >

"Hello world"

It can be used, but the problem I found is as follows: My intention is to paste each line into its own repetition without the extra line.

with open('domains.txt','r') as f:
    for line in f:
        test_var = line line
        print(test_var)

out:

"string
string
string2
string2
string3
string3"

so I want this output (without new line between that):

"string string
string2 string2
string3 string3"

CodePudding user response:

print() has an optional end parameter which defaults to \n, the newline character. If you specify print(Test_var, end=''), you'll be able to print without any space between the outputs. Then, you can manually print('\n') to control where your new lines end up!

That being said, I think you're also fighting a separate issue where the file is being read in with the newline characters still appended to the end of the line. Check out How to read a file without newlines? for advice on removing newline characters from the lines you're reading.

  • Related