0

the format of my .txt file looks like this:

a
abc
apple
hello

I am using this code to read them as string:

with open("wordsEn.txt") as infile:
    for line in infile:
        print(i)

My output is something like this where there is an additional line after each string. What went wrong there? How can I remove them? also the length of every string is not right.. where the first string 'a' 's legth is 2

a

abc

apple

hello
1
  • 1
    It is the same, but line also contains the tailing new line '\n' character. By default print(..) adds an additional new line. You can use print(line,end='') to prevent that. Commented Sep 2, 2017 at 19:32

1 Answer 1

0

print prints what you pass + \n. Lines have their own \n at the end. Use strip:

with open('wordsEn.txt') as file:
    for line in file:
        print(line.strip())

In Python 3 you can use end parameter for print function:

print(line, end='')
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.