I am new to python and stuck with some issue which could be pretty easy for python expert. I am trying to read text file in python but not getting desired out put using f string.
print(f'{lines[0]} {lines[2]}')\n
I am getting output in two lines, although I didn't use \\n
Hello
I am testing!
Expected output:
Hello I am testing!
It's because when you read a file at end of every line a newline character exists. So if you even print only one line you'll get a blank line after the text. You can solve it by using strip method:
print(f'{lines[0].strip()} {lines[2].strip()}')
As you can see in your text file, the text is in different lines, so python interpreted it as a newline. So, it added a new line character \\n
. You just have to strip the character.
print(f'{lines[0].strip('\n')} {lines[2].strip('\n')}')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.