在Python2和Python3中都提供print()方法來列印資訊,但兩個版本間的print稍微有差異
主要體現在以下幾個方面:
1.python3中print是一個內建函數,有多個參數,而python2中print是一個文法結構;
2.Python2列印時可以不加括弧:print 'hello world', Python3則需要加括弧 print("hello world")
3.Python2中,input要求輸入的字串必須要加引號,為了避免讀取非字串類型發生的一些行為,不得不使用raw_input()代替input()
1. python3中,或許開發人員覺得print同時具有兩重身份有些不爽,就只留了其中函數的身份:
>>> print 'pythontab.com'SyntaxError: Missing parentheses in call to 'print'
所以python3中print必須使用括弧,因為它就是一個函數。
2. python3中print函數有多個參數,函數原型如下:
print(value1, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
從上面的方法原型可以看出,
1. print可以支援多個參數,支援同時列印多個字串(其中...表示任意多個字串);
2. sep表示多個字串之間使用什麼字元串連;
3. end表示字串結尾添加什麼字元,指點該參數就可以輕鬆設定列印不換行,Python2.x下的print語句在輸出字串之後會預設換行,如果不希望換行,只要在語句最後加一個“,”即可。但是在Python 3.x下,print()變成內建函數,加“,”的老方法就行不通了。
>>> print("python", "tab", ".com", sep='')pythontab.com >>> print("python", "tab", ".com", sep='', end='') #就可以實現列印出來不換行pythontab.com
3.Python2中input的坑
print ("what do you like")a = input("Enter any content:")print ("i like",a)
輸入字串時會報錯,而在python3中很好地解決了這個問題。