Python2和Python3中print的不同點

來源:互聯網
上載者:User
在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中很好地解決了這個問題。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.