0

I have a file named numbers.txt and this is the content:

1
2
3
4

This is the code I used to read the lines in numbers.txt:

with open("numbers.txt") as numbers:
    for number in numbers:
        try:
            print(number + ' is a number!')
        except Exception as e:
            print(e)

Output:

1
 is a number!
2
 is a number!
3
 is a number!
4 is a number!

I wanted it to output this:

1 is a number!
2 is a number!
3 is a number!
4 is a number!

How can I get this output?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
iksskjj
  • 49
  • 7

1 Answers1

2

You can use strip function to get rid of \n char at the end of the lines.

with open("numbers.txt") as numbers:
    for number in numbers:
        try:
            print(number.strip() + ' is a number!')
        except Exception as e:
            print(e)

Produces following output

1 is a number!
2 is a number!
3 is a number!
4 is a number!
Ibrahim Berber
  • 842
  • 2
  • 16