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文件以文本形式打开可以,浏览器打开乱码)。
在实践中遇到乱七八糟的问题很多,基本是靠网络,谷歌解决的(有些时候的想放弃,但一定要坚持)