2013-04-25 31 views
0

我正在學習python,並遇到了困惑我的這種行爲。print()Python中的2個變量3.3

爲什麼這段代碼打印出來的括號和\r\n包圍的變量:

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

current_line = 1 
print_a_line(current_line, current_file) 

打印:

(1, 'a1\r\n') 

而這段代碼:

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

current_line = 1 
print_a_line(current_line, current_file) 

打印不帶括號:

a1 
+0

您使用的是Python 2. – Volatility 2013-04-25 23:17:25

+0

我猜這不是真正的python 3.3。 – 2013-04-25 23:17:28

+1

對不起,我不小心搬到了Python 2的mac。 – Nyxynyx 2013-04-25 23:20:53

回答

2

在第一種情況下,當你print(line_count, f.readline())你實際上是在說打印一個元組,其中第一個元素是line_count和第二個元素是f.readline()f.readline()讀取整條生產線,以線標誌的結束,在你的文件時,它是'\ r \ n'。

在第二種情況下,print (f.readline()),要打印只是一個字符串,不包含字符串,(一個元組,如果你想包含只是一個字符串的元組,你應該使用(mystring,)

(anystring)符號讓你用途:

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

相反的print(line_count, f.readline()),你應該使用

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

print ('%d %s'%(line_count, f.readline()))