Python2和3的主要區別,Python2區別

來源:互聯網
上載者:User

Python2和3的主要區別,Python2區別
一、print

在 python2 中 print 是一條語句,而在 python3 中 print 作為函數存在。

# python2>>> print ("hello")hello# python3 >>> print ("hello")hello

 

這樣看好像沒有什麼區別,python2 好像也可以把 print 當做函數使用,但是僅僅是表象而已,前者是把 ("hello")當作一個整體,而後者 print()是個函數,接收字串作為參數。

#python2>>> print ("hello","world")('hello', 'world')#python3>>> print ("hello","world")hello world

 

這樣看就非常明顯了,python2 中,print 語句後接的是元組對象 ("hello","world")。

而 python3 中,print() 函數是得到了兩個位置參數 hello 和 world 。

如果想在 python2 中把 print 當做函數使用,可以匯入 __future__ 模組中的 print_function

>>> print ("Hello","world")('Hello', 'world')>>> >>> from __future__ import print_function>>> print ("Hello","world")Hello world

 

 二、編碼

python2 預設編碼是 asscii,所以不能直接列印中文,如果要在指令碼中使用中文,需要在指令碼中聲明使用utf-8,# -*- coding: utf-8 -*-,

#!/usr/bin/env python# -*- coding: utf-8 -*-print "您好"

 

而在 python3 中,預設編碼已經是 utf-8 了,所以已經不需要單獨聲明了,可以直接列印中文內容。

#!/usr/bin/env pythonprint ("您好")

 

 三、使用者輸入

python 2 使用者輸入使用 raw_input(),python 3 使用 input(),python2 中也可以使用 input(),但是參數只能是變數,不推薦在python 2 中使用 input()。

#!/usr/bin/env python#user_input = raw_input("Please input something: ") #only on python 2.xuser_input = input("Please input something: ")print(user_input)

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.