0

I'm learning python and came across this behavior which puzzles me.

Why does this code print out the variables enclosed by parenthesis and \r\n:

def print_a_line(line_count, f):
    print(line_count, f.readline())

current_line = 1
print_a_line(current_line, current_file)

Prints:

(1, 'a1\r\n')

while this code:

def print_a_line(line_count, f):
    print(f.readline())

current_line = 1
print_a_line(current_line, current_file)

prints without the parenthesis:

a1
4
  • You're using Python 2. Commented Apr 25, 2013 at 23:17
  • I'm guessing it's not really python 3.3. Commented Apr 25, 2013 at 23:17
  • 1
    Sorry, I accidentally moved to a mac with Python 2. Commented Apr 25, 2013 at 23:20
  • @Nyxynyx Did my answer helped... if so, accept it please. And by the way, what kind of accident did move you to a mac? :) Commented Apr 22, 2014 at 16:13

1 Answer 1

2

In the first case, when you print(line_count, f.readline()) you are actually saying print a tuple, which first element is line_count and the second element is f.readline(), f.readline() reads the entire line, with the end of line marker, in your file it is '\r\n'.

In the second case, print (f.readline()), you are printing just a string, not a tuple containing a string, (if you want a tuple containing just a string you should use (mystring,).

The (anystring) notation allows you to use:

mystring = ('This is my '
            'very long string')

Instead of print(line_count, f.readline()) you should use

print (str(line_count) + f.readline())

or

print ('%d %s'%(line_count, f.readline()))
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.