码迷,mamicode.com
首页 > 编程语言 > 详细

python 快速入门

时间:2015-04-13 14:21:21      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:

一、字符串

  python中字符被定义为引号之间的字符集合,使用索引操作符([])和切片操作符([:])可以等到子字符串。字符串有其特有的索引规则:第一个字符的索引是0,最后一个字符的索引是-1。

  加号(+)用于字符串连接运算,星号(*)则用于字符串重复。

下面分别举例:

>>> pystr=‘python‘
>>> isool=‘is cool!‘
>>> pystr[0]
‘p‘
>>> pystr[2:5]
‘tho‘
>>> isool[:2]
‘is‘
>>> isool[:1]
‘i‘
>>> isool[-1]
‘!‘
>>> isool[-2]
‘l‘
>>> pystr + isool
‘pythonis cool!‘
>>> pystr + ‘ ‘ + isool
‘python is cool!‘
>>> pystr * 2
‘pythonpython‘
>>> ‘-‘ * 2
‘--‘

>>> pystr = ‘‘‘python
... is cool‘‘‘
>>> pystr
‘python\nis cool‘
>>> print pystr
python
is cool

 

二、列表和元组

  可以将列表和元组当成普通的 “数组”,它能保存任意数量类型的python对象,和数组一样,通过从0开始的数字索引访问元素,但是列表和元组可以存储不同类型的对象。

  列表和元组有几处重要的区别。列表元素用中括号([])包裹,元素的个数及元素的值可以改变。

  元组元素用小括号(())包裹,不可以更改(尽管他们的内容可以)。元组可以看成是只读的列表。通过切片运算([] 和 [:])可以得到子集,这一点与字符串的使用方法一样,当然列表和元组是可以互相转换的。

举例:

>>> alist=[1,2,3,4]
>>> alist
[1, 2, 3, 4]
>>> alist[0]
1
>>> alist[1]
2

>>> alist[1] = 5
>>> alist
[1, 5, 3, 4]
>>> alist[1:3]
[5, 3]

== 元组也可以进行切片运算,得到的结果也是元组(不可更改)

 

>>> atuple = (‘a‘,‘b‘,‘c‘,‘d‘)
>>> atuple
(‘a‘, ‘b‘, ‘c‘, ‘d‘)
>>> atuple[:3]
(‘a‘, ‘b‘, ‘c‘)
>>> atuple[0:3]
(‘a‘, ‘b‘, ‘c‘)
>>> atuple[3]
‘d‘
>>> atuple[6]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: tuple index out of range

      == 元组和列表互转

>>> alist
[1, 5, 3, 4]
>>> atuple
(‘a‘, ‘b‘, ‘c‘, ‘d‘)
>>> tuple(alist)
(1, 5, 3, 4)
>>> list(atuple)
[‘a‘, ‘b‘, ‘c‘, ‘d‘]

 

三、字典

  字典是python中的映射数据类型,工作原理类似perl中的关联数组或哈希表,由键-值(key-value)对构成。几乎所有类型的python对角都可以用作键,不过一般还是以数字或都字符串最为常用。

  值可以是任意类型的python对象,字典元素用大括号({})包裹。

举例:

>>> adict = {‘host‘:‘localhost‘}
>>> adict
{‘host‘: ‘localhost‘}
>>> adict[‘host‘]
‘localhost‘
>>> adict[‘localhost‘]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: ‘localhost‘
>>> adict[‘ip‘]=192.168.1.11
File "<stdin>", line 1
adict[‘ip‘]=192.168.1.11
^
SyntaxError: invalid syntax
>>> adict[‘ip‘]=‘192.168.1.11‘
>>> adict[‘ip‘]
‘192.168.1.11‘
>>> adict
{‘ip‘: ‘192.168.1.11‘, ‘host‘: ‘localhost‘}
>>> adict[‘port‘]=80
>>> adict
{‘ip‘: ‘192.168.1.11‘, ‘host‘: ‘localhost‘, ‘port‘: 80}
>>> adict[‘ipaddress‘]=‘192.168.1.11‘
>>> adict
{‘ip‘: ‘192.168.1.11‘, ‘host‘: ‘localhost‘, ‘ipaddress‘: ‘192.168.1.11‘, ‘port‘: 80}

 

四、if语句

  标准if条件语句的语法如下:

  if expression:

    if_suite

  如果表达式的值非0或者为布尔值True,则代码组if_suite被执行;否则就去扫行下一条语句。代码组(suite)是一个python术语,它由一条或多条语句组成,表示一个子代码块。python与其他语言不同,条件表达式并不需要用括号括起来。

  if x < 0:

    print ‘"x" must be atleast 0!‘

  也支持else语句,语法如下。

  if  expression:

    if_suite

  else:

    else_suite

  同样还支持elif语句,如下。 

  if  expression1:

    if_suite

  elif expression2:

    elif_suite

  else:

    else_suite

 

python 快速入门

标签:

原文地址:http://www.cnblogs.com/wangbaigui/p/4421920.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!