pythonfordataan
「python編程輸入n.求平均數」
==>
輸入n個正整數,計算其平均值
==>
defenterInteger(prompt="Enteraninteger:"):
"""promptinputaninteger"""
while1:
try:
returnint(raw_input(prompt))
except:
pass
defmain(n):
data=[enterInteger()forxinxrange(n)]
ifdata:
print"Avg:%.2f"%(1.*sum(data)/len(data))
if__name__=="__main__":
main(5)
Ⅱ 有沒有Python中的函數來列印一個對象的所有當前的屬性和值
1. 你是兩個不同的事情真的混在一起。
使用dir()或inspect模塊讓你有興趣(什麼__builtins__作為一個例子,你的任何對象,而不是)。
>>> l = dir(__builtins__)
>>> d = __builtins__.__dict__
列印該字典但是看上你喜歡:
>>> print l
['ArithmeticError', 'AssertionError', 'AttributeError',...
或
>>> from pprint import pprint
>>> pprint(l)
['ArithmeticError',
'AssertionError',
'AttributeError',
'BaseException',
'DeprecationWarning',
...
>>> pprint(d, indent=2)
{ 'ArithmeticError': <type 'exceptions.ArithmeticError'>,
'AssertionError': <type 'exceptions.AssertionError'>,
'AttributeError': <type 'exceptions.AttributeError'>,
...
'_': [ 'ArithmeticError',
'AssertionError',
'AttributeError',
'BaseException',
'DeprecationWarning',
...
2.
你想瓦爾()與PPRINT混合:
from pprint import pprint
pprint (vars(your_object))
3.
def mp(obj):
for attr in dir(obj):
print "obj.%s = %s" % (attr, getattr(obj, attr))
4.
目錄有但只會給你的屬性'如果你希望自己的價值觀,以及嘗試的__dict__。
class O:
def __init__ (self):
self.value = 3
o = O()
>>> o.__dict__
{'值':3}
5.
你的「目錄()」函數來做到這一點。
>>> import sys
>>> dir(sys)
['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__', '__stdin__', '__stdo
t__', '_current_frames', '_getframe', 'api_version', 'argv', 'builtin_mole_names', 'byteorder
, 'call_tracing', 'callstats', 'right', 'displayhook', 'dllhandle', 'exc_clear', 'exc_info'
'exc_type', 'excepthook', 'exec_prefix', 'executable', 'exit', 'getcheckinterval', 'getdefault
ncoding', 'getfilesystemencoding', 'getrecursionlimit', 'getrefcount', 'getwindowsversion', 'he
version', 'maxint', 'maxunicode', 'meta_path', 'moles', 'path', 'path_hooks', 'path_importer_
ache', 'platform', 'prefix', 'ps1', 'ps2', 'setcheckinterval', 'setprofile', 'setrecursionlimit
, 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version', 'version_info', 'warnoption
', 'winver']
>>>
函數是幫助。
>>> help(sys)
Help on built-in mole sys:
NAME
sys
FILE
(built-in)
MODULE DOCS
CodeGo.net
DESCRIPTION
This mole provides access to some objects used or maintained by the
interpreter and to functions that interact strongly with the interpreter.
Dynamic objects:
argv -- command line arguments; argv[0] is the script pathname if known
6.
要列印的對象,你可能的當前狀態:
>>> obj # in an interpreter
或
print repr(obj) # in a script
或
print obj
為你的類定義__str__或__repr__方法。從Python__repr__(self)由被叫repr()內置函數和字元串
轉換(反引號)
計算「官方」的字元串
一個對象的表示。如果在所有
可能的話,這應該看起來像一個
有效的Python表達式,可能是
用於重新創建的對象與
值(給定一個適當的
如果這是不可能的 CodeGo.net,
一個字元串表單的「<...有用
描述...>「應該返回。
返回值必須是一個字元串
對象。如果一個類定義再版()
但不__str__(),然後__repr__()是
當一個「非正式」的字元串
的該實例的代表性
類是必需的。這通常是
用於調試,所以重要的是
該項表示是
信息豐富,__str__(self)由被叫str()內置函數和由列印
「非正式」
一個對象的字元串表示表單。
這不同於__repr__()在這
它並不必須是一個有效的Python
表達式:更方便或
簡潔的表述,如
代替。返回值必須是一個
字元串對象。
7.
可能是值得一試-
是否有相當於Perl的Data ::自卸車一個Python?
我是這樣的-
需要注意的是Perl有一個名為Data ::
Dumper模塊的轉換對象數據返回到perl的源代碼(註:它並沒有轉化代碼回到源,而且幾乎總是你不想在輸出的函數)。這可持久性,但目的是為了調
試。
有許多事情標準的python
PPRINT未能達到,尤其是剛剛停止時,看到一個對象的實例,並為您的對象的內六角指針(降序呃,這個指針是不是一大堆的方式)。因此,概括地
說,python是所有關於這個偉大的面向對象的範式,但你得到的開箱即用的工具是專為與對象比其他工作。
在Perl的Data ::
Dumper允許你控制你想有多深去,並且還檢測循環鏈表結構(這是非常重要的)。這個過程是比較容易實現的perl的對象有超越他們的祝福沒有特別的魔
法(一個普遍良好定義的線程)。
8.
在大多數情況下,使用__dict__或dir()你將會得到你想要。如果您碰巧需要更多的細節,標准庫包含了inspect模塊,它可以讓你獲得細節令人印象深刻的金額。真正的nuggests包括:
函數
類層次結構
的一個函數/類對象的源代碼
局部變數出對象的
如果你只是尋找「沒有我的對象有什麼屬性值?」,然後dir()和__dict__可能是足夠的。如果你真的希望挖掘到任意對象的當前狀態(牢記在python幾乎一切都是對象),然後inspect是值得考慮的。
9.
例如轉儲對象的魔法:
$貓mp.py
#!/usr/bin/python
import sys
if len(sys.argv) > 2:
mole, metaklass = sys.argv[1:3]
m = __import__(mole, globals(), locals(), [metaklass])
__metaclass__ = getattr(m, metaklass)
class Data:
def __init__(self):
self.num = 38
self.lst = ['a','b','c']
self.str = 'spam'
mps = lambda self: repr(self)
__str__ = lambda self: self.mps()
data = Data()
print data
無
$pythonmp.py
<__main__.Data instance at 0x00A052D8>
與靈知utils的:
$pythonmp.py gnosis.magic MetaXMLPickler
<?xml version="1.0"?>
<!DOCTYPE PyObject SYSTEM "PyObjects.dtd">
<PyObject mole="__main__" class="Data" id="11038416">
<attr name="lst" type="list" id="11196136" >
<item type="string" value="a" />
<item type="string" value="b" />
<item type="string" value="c" />
</attr>
<attr name="num" type="numeric" value="38" />
<attr name="str" type="string" value="spam" />
</PyObject>
這是一個有點過時,但仍然堅持工作。
10.
PPRINT包含一個「漂亮的列印機」為你製造數據結構的美觀交涉。格式化器產生的數據結構的表示,可以正確地由解釋器進行解析,並且也很容易對一個人的閱讀。輸出保持在一行上,如果可能的話,與縮進時,多行拆分。
11.
為什麼不能簡單的:
關鍵,在obj的值。字典iteritems()。:
列印鍵,值
12.
我需要在日誌中列印並無法PPRINT它會打破它。相反,我這樣做,並幾乎得到了的東西。
DO = DemoObject()
itemDir = DO.__dict__
for i in itemDir:
print '{0} : {1}'.format(i, itemDir[i])
Ⅲ coursera上有哪些值得學習的Python,數據分析的課程
01- Toolbox of Data Scientist
介紹數據科學一些基本的概念,教你怎麼開始使用github,安裝R,等等。4quiz,最後final project就是開通github賬號然後進行一些操作什麼的。無coding,難度較低。
02- R Programming
就是R programming啦。Quiz較簡單。programming assignment有三個,需要coding,對於我這個之前從來沒用過github不會編程的菜鳥來講還是蠻有難度的。
06- Statistical Inference
統計學基本知識,有統計學基礎的話學起來還挺輕松。4個quiz,final project有兩部分,簡單分析一些數據,不難。沒有coding任務,但是做quiz和分析數據的時候需要用到R programming
目前正在修03- Getting & Cleaning Data
·University of Michigan的Learn to Program and Analyze Data with Python,四門課+一個capstone。顧名思義,以Python為主幹。
目前只修了第一門Programming for Everybody (Getting Started with Python)。怎麼說呢……這門課真的是……太簡單了……
身為一個編程幾乎無基礎的小弱,兩天就上完了……
特么的print 『hello world』都能算一個assignment我也是醉了……
老師比較搞笑,會用很多例子來解釋一些問題。但是干貨略少,因此不建議花錢上這門。
每周都會有一些彩蛋視頻,比如老師又去哪裡玩了,比如成功創業者程序員的訪談,還是挺inspiring的。
第二門要到十月下旬才開新的session,等我上了再答。
目前剛開始上Rice的An Introction to Interactive Programming in Python,暫時不評價。
此外,身為生物狗,我還上了一些生信相關的,不是很對題不過也寫上吧(其實寫上是為了裝逼):
·又是JHU的,Genomic Data Science Specialization,七門課+一個capstone。涉及python,R等多種軟體/語言。
01- Introction to Genomic Technologies
一般叫Introction的都挺簡單的,你懂得。4個quiz,最後final是讀一篇文章回答幾個問題。無coding
03- Python for Genomic Data Science
教你用Python進行一些基本的序列分析,比如數鹼基找pattern什麼的,目前正在上。女老師口音略醉人。
06- Bioconctor for Genomic Data Science
Bioconctor上有很多有用的生信R package,這門課的主要內容就是教人使用這些包。我之前上了一點,後來時間不夠就退了。
·UCSD的bioinformatics,六門課+一個capstone
01- Finding Hidden Messages in DNA
講了一些基本演算法,教你怎麼在DNA序列中找pattern啊,找motif啊,等等。
無coding assignment,但是問題都需要用coding解決,會提供pseudocode。
感覺上完一遍後編程提高挺多的。再次證明getting your hands dirty是學編程的最好辦法。
Ⅳ Python 的 type 和 object 之間是怎麼一種關系
Python的object和type理解
1、節選自Python Documentation 3.5.2的部分解釋
Objects are Python』s abstraction for data. All data in a Python program is represented by objects or by relations between objects. (In a sense, and in conformance to Von Neumann』s model of a 「stored program computer,」 code is also represented by objects.)
對象是Python對數據的抽象。 Python程序中的所有數據都由對象或對象之間的關系表示。(在某種意義上,並且符合馮·諾依曼的「存儲程序計算機」的模型,代碼也由對象表示的)。
Every object has an identity, a type and a value. An object』s identity never changes once it has been created; you may think of it as the object』s address in memory. The 『is『 operator compares the identity of two objects; the id() function returns an integer representing its identity.
每個對象都有一個標識,一個類型和一個值。 對象的身份一旦創建就不會改變; 你可以把它看作內存中的對象地址。'is'運算符比較兩個對象的標識; id()函數返回一個表示其身份的整數。
An object』s type determines the operations that the object supports (e.g., 「does it have a length?」) and also defines the possible values for objects of that type. The type() function returns an object』s type (which is an object itself). Like its identity, an object』s type is also unchangeable.
對象的類型決定對象支持的操作(例如,「它有長度嗎?」),並且還定義該類型對象的可能值。type()函數返回一個對象的類型(它是一個對象本身)。與它的身份一樣,對象的類型也是不可改變的。
2、Pyhtml的解釋:
object:
class object
The most base type
type:
class type(object)
type(object_or_name, bases, dict)
type(object) -> the object's type
type(name, bases, dict) -> a new type
從上面三個圖可以看出,對象obeject是最基本的類型type,它是一個整體性的對數據的抽象概念。相對於對象object而言,類型type是一個稍微具體的抽象概念,說它具體,是因為它已經有從對象object細化出更具體抽象概念的因子,這就是為什麼type(int)、type(float)、type(str)、type(list)、type(tuple)、type(set)等等的類型都是type,這也是為什麼instance(type, object)和instance(object, type)都為True的原因,即類型type是作為int、float等類型的整體概念而言的。那麼,為什麼issubclass(type, object)為True,而issubclass(object, type)為Flase呢?從第二張圖,即從繼承關系可以看到,type是object的子類,因此前者為True,後者為False。若從Python語言的整體設計來看,是先有對象,後有相對具體的類型,即整體優先於部分的設計思想。
如果從更加本質的視角去看待這些問題的話,就要從Python Documentation-->3. Data Model-->3.1 Objects,values and types找原因了[請參考Python官方標准庫],從標准庫里可以看到:
object是Python對數據的抽象,它是Python程序對數據的集中體現。
每個對象都有一個標識,一個類型和一個值。
對象的類型決定對象支持的操作。
某些對象的值可以更改。 其值可以改變的對象稱為可變對象;對象的值在創建後不可更改的對象稱為不可變對象。
因此,從Python整體設計體系來看的話,就是先有對象,再有標識、類型和值,接著是對對象的操作等等,這也就解釋了圖3的結果形成的原因了。
Ⅳ Python中 for 語句的用法
guess=int(input("enter
an
integer"))
這一句最後是兩個右括弧,分別與input和int函數對應,你只寫了一個
最後
一句
print('done')
加上引號,done不是內部變數
Ⅵ python3.6程序運行出錯,下面是提示 Traceback (most recent call last):
樓上說的不對,出的錯與單引號無關,是編碼的問題。你的代碼本身沒錯,把你現在的文件刪掉,重新建一個就行。下面和你的一樣,只是換了路徑,測試可行
1234567891011121314src_path = 'E:\\test_0.txt'des_path = 'E:\\test_1.txt' file_wait_to_read = open(src_path, 'r')file_wait_to_write = open(des_path, 'w') <a href="https://www..com/s?wd=sat&tn=44039180_cpr&fenlei=_5y9YIZ0lQzqlpA-" target="_blank" class="-highlight">sat</a> = raw_input('Please input the selected <a href="https://www..com/s?wd=sat&tn=44039180_cpr&fenlei=_5y9YIZ0lQzqlpA-" target="_blank" class="-highlight">sat</a>ellite: ')for line in file_wait_to_read.readlines(): if line.startswith(<a href="https://www..com/s?wd=sat&tn=44039180_cpr&fenlei=_5y9YIZ0lQzqlpA-" target="_blank" class="-highlight">sat</a>): file_wait_to_write.write(line) file_wait_to_write.flush()file_wait_to_read.close()file_wait_to_write.close()
Ⅶ 如何通過 Python 使用 Azure Blob 存儲
Overview
Azure Blob storage is a service that stores unstructured data in the cloud as objects/blobs. Blob storage can store any type of text or binary data, such as a document, media file, or application installer. Blob storage is also referred to as object storage.
This article will show you how to perform common scenarios using Blob storage. The samples are written in Python and use theMicrosoft Azure Storage SDK for Python. The scenarios covered include uploading, listing, downloading, and deleting blobs.
What is Blob Storage?
Azure Blob storage is a service for storing large amounts of unstructured object data, such as text or binary data, that can be accessed from anywhere in the world via HTTP or HTTPS. You can use Blob storage to expose data publicly to the world, or to store application data privately.
Common uses of Blob storage include:
Serving images or documents directly to a browser
Storing files for distributed access
Streaming video and audio
Storing data for backup and restore, disaster recovery, and archiving
Storing data for analysis by an on-premises or Azure-hosted service
Storage Account:All access to Azure Storage is done through a storage account. This storage account can be aGeneral-purpose storage accountor aBlob storage accountwhich is specialized for storing objects/blobs. SeeAbout Azure storage accountsfor more information.
Container:A container provides a grouping of a set of blobs. All blobs must be in a container. An account can contain an unlimited number of containers. A container can store an unlimited number of blobs. Note that the container name must be lowercase.
Blob:A file of any type and size. Azure Storage offers three types of blobs: block blobs, page blobs, and append blobs.
Block blobsare ideal for storing text or binary files, such as documents and media files.Append blobsare similar to block blobs in that they are made up of blocks, but they are optimized for append operations, so they are useful for logging scenarios. A single block blob can contain up to 50,000 blocks of up to 100 MB each, for a total size of slightly more than 4.75 TB (100 MB X 50,000). A single append blob can contain up to 50,000 blocks of up to 4 MB each, for a total size of slightly more than 195 GB (4 MB X 50,000).
Page blobscan be up to 1 TB in size, and are more efficient for frequent read/write operations. Azure Virtual Machines use page blobs as OS and data disks.
For details about naming containers and blobs, seeNaming and Referencing Containers, Blobs, and Metadata.
- pip install azure-storage-blob
- from azure.storage.blob import BlockBlobService
- block_blob_service = BlockBlobService(account_name='myaccount', account_key='mykey')
Container names must start with a letter or number, and can contain only letters, numbers, and the dash (-) character.
Every dash (-) character must be immediately preceded and followed by a letter or number; consecutive dashes are not permitted in container names.
All letters in a container name must be lowercase.
Container names must be from 3 through 63 characters long.
- block_blob_service.create_container('mycontainer')
- from azure.storage.blob import PublicAccess
- block_blob_service.create_container('mycontainer', public_access=PublicAccess.Container)
- block_blob_service.set_container_acl('mycontainer', public_access=PublicAccess.Container)
- from azure.storage.blob import ContentSettings
- block_blob_service.create_blob_from_path( 'mycontainer', 'myblockblob', 'sunset.png',
- content_settings=ContentSettings(content_type='image/png')
- )
- generator = block_blob_service.list_blobs('mycontainer')for blob in generator:
- print(blob.name)
- block_blob_service.get_blob_to_path('mycontainer', 'myblockblob', 'out-sunset.png')
- block_blob_service.delete_blob('mycontainer', 'myblockblob')
- from azure.storage.blob import AppendBlobService
- append_blob_service = AppendBlobService(account_name='myaccount', account_key='mykey')# The same containers can hold all types of blobsappend_blob_service.create_container('mycontainer')# Append blobs must be created before they are appended toappend_blob_service.create_blob('mycontainer', 'myappendblob')
- append_blob_service.append_blob_from_text('mycontainer', 'myappendblob', u'Hello, world!')
- append_blob = append_blob_service.get_blob_to_text('mycontainer', 'myappendblob')
Blob service concepts
The Blob service contains the following components:
Create an Azure storage account
The easiest way to create your first Azure storage account is by using theAzure portal. To learn more, seeCreate a storage account.
You can also create an Azure storage account by usingAzure PowerShell,Azure CLI, or theStorage Resource Provider Client Library for .NET.
If you prefer not to create a storage account at this time, you can also use the Azure storage emulator to run and test your code in a local environment. For more information, seeUse the Azure Storage Emulator for Development and Testing.
Download and Install Azure Storage SDK for Python
Azure Storage SDK for Python requires Python 2.7, 3.3, 3.4, 3.5, or 3.6, and comes in 4 different packages:azure-storage-blob,azure-storage-file,azure-storage-tableandazure-storage-queue. In this tutorial we are going to useazure-storage-blobpackage.
Install via PyPi
To install via the Python Package Index (PyPI), type:
bashCopy
Note
If you are upgrading from the Azure Storage SDK for Python version 0.36 or earlier, you will first need to uninstall usingpip uninstall azure-storageas we are no longer releasing the Storage SDK for Python in a single package.
For alternative installation methods, visit theAzure Storage SDK for Python on Github.
Create a container
Based on the type of blob you would like to use, create aBlockBlobService,AppendBlobService, orPageBlobServiceobject. The following code uses aBlockBlobServiceobject. Add the following near the top of any Python file in which you wish to programmatically access Azure Block Blob Storage.
PythonCopy
The following code creates aBlockBlobServiceobject using the storage account name and account key. Replace 'myaccount' and 'mykey' with your account name and key.2
PythonCopy
Every blob in Azure storage must reside in a container. The container forms part of the blob name. For example,mycontaineris the name of the container in these sample blob URIs:2
Copy
A container name must be a valid DNS name, conforming to the following naming rules:
Important
Note that the name of a container must always be lowercase. If you include an upper-case letter in a container name, or otherwise violate the container naming rules, you may receive a 400 error (Bad Request).
In the following code example, you can use aBlockBlobServiceobject to create the container if it doesn't exist.
PythonCopy
By default, the new container is private, so you must specify your storage access key (as you did earlier) to download blobs from this container. If you want to make the blobs within the container available to everyone, you can create the container and pass the public access level using the following code.
PythonCopy
Alternatively, you can modify a container after you have created it using the following code.
PythonCopy
After this change, anyone on the Internet can see blobs in a public container, but only you can modify or delete them.
Upload a blob into a container
To create a block blob and upload data, use thecreate_blob_from_path,create_blob_from_stream,create_blob_from_bytesorcreate_blob_from_textmethods. They are high-level methods that perform the necessary chunking when the size of the data exceeds 64 MB.
create_blob_from_pathuploads the contents of a file from the specified path, andcreate_blob_from_streamuploads the contents from an already opened file/stream.create_blob_from_bytesuploads an array of bytes, andcreate_blob_from_textuploads the specified text value using the specified encoding (defaults to UTF-8).
The following example uploads the contents of thesunset.pngfile into themyblockblobblob.
PythonCopy
List the blobs in a container
To list the blobs in a container, use thelist_blobsmethod. This method returns a generator. The following code outputs thenameof each blob in a container to the console.
PythonCopy
Download blobs
To download data from a blob, useget_blob_to_path,get_blob_to_stream,get_blob_to_bytes, orget_blob_to_text. They are high-level methods that perform the necessary chunking when the size of the data exceeds 64 MB.
The following example demonstrates usingget_blob_to_pathto download the contents of themyblockblobblob and store it to theout-sunset.pngfile.2
PythonCopy
Delete a blob
Finally, to delete a blob, calldelete_blob.
PythonCopy
Writing to an append blob
An append blob is optimized for append operations, such as logging. Like a block blob, an append blob is comprised of blocks, but when you add a new block to an append blob, it is always appended to the end of the blob. You cannot update or delete an existing block in an append blob. The block IDs for an append blob are not exposed as they are for a block blob.
Each block in an append blob can be a different size, up to a maximum of 4 MB, and an append blob can include a maximum of 50,000 blocks. The maximum size of an append blob is therefore slightly more than 195 GB (4 MB X 50,000 blocks).
The example below creates a new append blob and appends some data to it, simulating a simple logging operation.
PythonCopy
Ⅷ python3.4學習筆記 3.x和2.x的區別,持續更新
python3.4學習筆記(四) 3.x和2.x的區別
在2.x中:print html,3.x中必須改成:print(html)
import urllib2
ImportError: No mole named 'urllib2'
在python3.x裡面,用urllib.request代替urllib2
import thread
ImportError: No mole named 'thread'
在python3.x裡面,用_thread(在前面加一個下劃線)代替thread
在2.x中except Exception,e : 3.x中改為except (Exception):
=================================
print函數
雖然print語法是Python 3中一個很小的改動,且應該已經廣為人知,但依然值得提一下:Python 2中的print語句被Python 3中的print()函數取代,這意味著在Python 3中必須用括弧將需要輸出的對象括起來。
在Python 2中使用額外的括弧也是可以的。但反過來在Python 3中想以Python2的形式不帶括弧調用print函數時,會觸發SyntaxError。
Python 2.7.6
print 'Python', python_version()
print 'Hello, World!'
print('Hello, World!')
print "text", ; print 'print more text on the same line'
輸出:
Hello, World!
Hello, World!
text print more text on the same line
---------------------------
Python 3.4.1
print('Python', python_version())
print('Hello, World!')
print("some text,", end="")
print(' print more text on the same line')
輸出:
Hello, World!
some text, print more text on the same line
print 'Hello, World!'
File "<ipython-input-3-139a7c5835bd>", line 1
print 'Hello, World!'
^
SyntaxError: invalid syntax
注意:在Python中,帶不帶括弧輸出」Hello World」都很正常。
但如果在圓括弧中同時輸出多個對象時,就會創建一個元組,這是因為在Python 2中,print是一個語句,而不是函數調用。
print 'Python', python_version()
print('a', 'b')
print 'a', 'b'
Python 2.7.7
('a', 'b')
a b
---------------------------------
整數除法
由於人們常常會忽視Python 3在整數除法上的改動(寫錯了也不會觸發Syntax Error),所以在移植代碼或在Python 2中執行Python 3的代碼時,需要特別注意這個改動。
所以,我還是會在Python 3的腳本中嘗試用float(3)/2或 3/2.0代替3/2,以此來避免代碼在Python
2環境下可能導致的錯誤(或與之相反,在Python 2腳本中用from __future__ import division來使用Python
3的除法)。
Python 2.7.6
3 / 2 = 1
3 // 2 = 1
3 / 2.0 = 1.5
3 // 2.0 = 1.0
Python 3.4.1
3 / 2 = 1.5
3 // 2 = 1
3 / 2.0 = 1.5
3 // 2.0 = 1.0
---------------------------------
Unicode
Python 2有基於ASCII的str()類型,其可通過單獨的unicode()函數轉成unicode類型,但沒有byte類型。
而在Python 3中,終於有了Unicode(utf-8)字元串,以及兩個位元組類:bytes和bytearrays。
Python 2.7.6
print type(unicode('this is like a python3 str type'))
<type 'unicode'>
print type(b'byte type does not exist')
<type 'str'>
print 'they are really' + b' the same'
they are really the same
print type(bytearray(b'bytearray oddly does exist though'))
<type 'bytearray'>
Python 3.4.1 has <class 'bytes'>
print('and Python', python_version(), end="")
print(' also has', type(bytearray(b'bytearrays')))
and Python 3.4.1 also has <class 'bytearray'>
1
'note that we cannot add a string' + b'bytes for data'
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-13-d3e8942ccf81> in <mole>()
----> 1 'note that we cannot add a string' + b'bytes for data'
TypeError: Can't convert 'bytes' object to str implicitly
=================================
python 2.4 與 python 3.0 的比較
一、 print 從語句變為函數
原: print 1,2+3
改為: print ( 1,2+3 )
二、range 與 xrange
原 : range( 0, 4 ) 結果 是 列表 [0,1,2,3 ]
改為:list( range(0,4) )
原 : xrange( 0, 4 ) 適用於 for 循環的變數控制
改為:range(0,4)
三、字元串
原: 字元串以 8-bit 字元串存儲
改為: 字元串以 16-bit Unicode 字元串存儲
四、try except 語句的變化
在2.x中except Exception,e : 3.x中改為except (Exception):
五、打開文件
原: file( ..... )
或 open(.....)
改為:
只能用 open(.....)
六、從鍵盤錄入一個字元串
原: raw_input( "提示信息" )
改為: input( "提示信息" )
七、bytes 數據類型
A bytes object is an immutable array. The items are 8-bit bytes, represented by integers in the range 0 <= x < 256.
bytes 可以看成是「位元組數組」對象,每個元素是 8-bit 的位元組,取值范圍 0~255。
由於在 python 3.0中字元串以 unicode 編碼存儲,當寫入二進制文件時,字元串無法直接寫入(或讀取),必須以某種方式的編碼為位元組序列後,方可寫入。
(一)字元串編碼(encode) 為 bytes
例: s = "張三abc12"
b = s.encode( 編碼方式)
# b 就是 bytes 類型的數據
# 常用的編碼方式為 : "uft-16" , "utf-8", "gbk", "gb2312", "ascii" , "latin1" 等
# 注 : 當字元串不能編碼為指定的「編碼方式」時,會引發異常
(二) bytes 解碼(decode)為字元串
s = "張三abc12"
b = s.encode( "gbk") # 字元串 s 編碼為 gbk 格式的位元組序列
s1 = b.decode("gbk") # 將位元組序列 b以gbk格式 解碼為字元串
# 說明,當位元組序列不能以指定的編碼格式解碼時會引發異常
(三)使用方法舉例
#coding=gbk
f = open("c:\\1234.txt", "wb")
s = "張三李四abcd1234"
# -------------------------------
# 在 python2.4 中我們可以這樣寫:
# f.write( s )
# 但在 python 3.0中會引發異常
# -------------------------------
b = s.encode("gbk")
f.write( b )
f.close()
input("?")
讀取該文件的例子:
#coding=gbk
f = open("c:\\1234.txt", "rb")
f.seek(0,2) #定位至文件尾
n = f.tell() #讀取文件的位元組數
f.seek(0,0) #重新定位至文件開始處
b = f.read( n )
# ------------------------------
# 在 python 2.4 中 b 是字元串類型
# 要 python 3.0 中 b 是 bytes 類型
# 因此需要按指定的編碼方式確碼
# ------------------------------
s = b.decode("gbk")
print ( s )
# ------------------------------
# 在 python 2.4 中 可以寫作 print s 或 print ( s )
# 要 python 3.0 中 必須寫作 print ( s )
# ------------------------------
f.close()
input("?")
運行後應顯示:
張三李四abcd1234
(四) bytes序列,一但形成,其內容是不可變的,例:
s="ABCD"
b=s.encode("gbk")
print b[0] # 顯示 65
b[0] = 66
# 執行該句,出現異常: 'bytes' object does not support item assignment
八、 chr( K ) 與 ord( c )
python 2.4.2以前
chr( K ) 將編碼K 轉為字元,K的范圍是 0 ~ 255
ord( c ) 取單個字元的編碼, 返回值的范圍: 0 ~ 255
python 3.0
chr( K ) 將編碼K 轉為字元,K的范圍是 0 ~ 65535
ord( c ) 取單個字元的編碼, 返回值的范圍: 0 ~ 65535
九、 除法運算符
python 2.4.2以前
10/3 結果為 3
python 3.0
10 / 3 結果為 3.3333333333333335
10 // 3 結果為 3
十、位元組數組對象 --- 新增
(一) 初始化
a = bytearray( 10 )
# a 是一個由十個位元組組成的數組,其每個元素是一個位元組,類型借用 int
# 此時,每個元素初始值為 0
(二) 位元組數組 是可變的
a = bytearray( 10 )
a[0] = 25
# 可以用賦值語句更改其元素,但所賦的值必須在 0 ~ 255 之間
(三) 位元組數組的切片仍是位元組數組
(四) 字元串轉化為位元組數組
#coding=gbk
s ="你好"
b = s.encode( "gbk") # 先將字元串按某種「GBK」編碼方式轉化為 bytes
c = bytearray( b ) #再將 bytes 轉化為 位元組數組
也可以寫作
c = bytearray( "你好", "gbk")
(五) 位元組數組轉化為字元串
c = bytearray( 4 )
c[0] = 65 ; c[1]=66; c[2]= 67; c[3]= 68
s = c.decode( "gbk" )
print ( s )
# 應顯示: ABCD
(六) 位元組數組可用於寫入文本文件
#coding=gbk
f = open("c:\\1234.txt", "wb")
s = "張三李四abcd1234"
# -------------------------------
# 在 python2.4 中我們可以這樣寫:
# f.write( s )
# 但在 python 3.0中會引發異常
# -------------------------------
b = s.encode("gbk")
f.write( b )
c=bytearray( "王五","gbk")
f.write( c )
f.close()
input("?")
Ⅸ 如何在實踐中學習Python
如果你是在校生,你可以加入相關實驗室。如果不是的話,有些python論壇或者編程論壇你可以進去看看,有相關項目練手。像碼雲,github上有很多python項目,你可以申請加入,當然要求較高。也可以把python2的程序用python3寫(網上大多是用2寫的爬蟲 學2的忽略)
我當時是在知乎,開源中國,還是開發者頭條中看到的,有一些前輩給出的建議。我就找了感興趣的練手,我寫了一些爬蟲:爬取網路圖片(不受『翻頁』限制),模擬登陸,cookie登陸等。
在實踐中你會發現很多問題,我寫第一個爬蟲是遇到了"編碼"問題,爬取的源碼出現亂碼情況。也出現過文件的保存問題(html文件以文本形式打開可以,瀏覽器打開亂碼)。
在實踐中遇到亂七八糟的問題很多,基本是靠網路,谷歌解決的(有些時候的想放棄,但一定要堅持)