Python 中字符串被定义为引号之间的字符集合。Python 支持使用成对的单引号或双引号,三引号(三个连续的单引号或者双引号)可以用来包含特殊字符。使用索引运算符( [ ] )和切片运算符( [ : ] )可以得到子字符串。字符串有其特有的索引规则:第一个字符的索引是 0,最后一个字符的索引是 -1
>>> str = 'Python'
>>> str[0] #str的第一个字符
'P'
>>> str[-1] #str的最后一个字符
'n'
>>> str[2:5] #切片操作 str的第二个-第四个字符
'tho'
>>> iscool = 'is cool!'
>>> iscool[:2] #切片操作 is cool的前两个字符
'is'
>>> iscool[3:] #切片操作 iscool第三个字符后面的所有字符
'cool!'
>>> str+iscool #连接操作
'Pythonis cool!'
>>> str+" "+iscool
'Python is cool!'
>>> '_'*20 #输出多个符号
'____________________'
>>>
列表和元组有几处重要的区别。列表元素用中括号( [ ])包裹,元素的个数及元素的值可以改变。元组元素用小括号(( ))包裹,不可以更改(尽管他们的内容可以)。元组可以看成是只读的列表。通过切片运算( [ ] 和 [ : ] )可以得到子集,这一点与字符串的使用方法一样。
>>> alist =[1,2,3,4]
>>> alist
[1, 2, 3, 4]
>>> alist[0]
1
>>> alist[2:]
[3, 4]
>>> alist[:3]
[1, 2, 3]
>>> alist[1]
2
>>> alist[1]=5 #列表信息可以被修改
>>> alist
[1, 5, 3, 4]
>>>
###############################
>>> phone =('nokia','sunsang','apple')
>>> phone
('nokia', 'sunsang', 'apple')
>>> phone[:3]
('nokia', 'sunsang', 'apple')
>>> phone[1] = 'chuizi' #元组信息不能被修改
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>>
字典是 Python 中的映射数据类型,工作原理类似 Perl 中的关联数组或者哈希表,由键-值(key-value)对构成。几乎所有类型的 Python 对象都可以用作键,不过一般还是以数字或者字符串最为常用。
值可以是任意类型的 Python 对象,字典元素用大括号({ })包裹。
>>> pyDict = {'football':'funny'} #字典用大括号包起来
>>> pyDict['pingpang']='very good' #也可以这样赋值
>>> pyDict
{'pingpang': 'very good', 'football': 'funny'}
>>> pyDict.keys() #显示所有的key
['pingpang', 'football']
>>> pyDict.values() #显示所有的value
['very good', 'funny']
>>> pyDict['pingpang'] #通过key找到对应的value
'very good'
Python 中的 for 循环与传统的 for 循环(计数器循环)不太一样, 它更象 shell 脚本里的 foreach 迭代。Python 中的 for 接受可迭代对象(例如序列或迭代器)作为其参数,每次迭代其中一个元素。
>>> item = {"python","is","most","language"}
>>> for items in item:
... print items
...
python #python默认在每一行后面添加一个换行符
most
is
language
>>>
##############
>>> item = {"python","is","most","language"}
>>> for items in item:
... print items, #添加,的结果
...
python most is language
>>>
##############为了输出清晰美观, 带逗号的 print 语句输出的元素之间会自动添加一个空格。通过指定输出格式, 程序员可以最大程度的控制输出布局, 也不用担心这些自动添加的空格。它也可以将所有数据放到一处输出--只需要将数据放在格式化运算符右侧的元组或字典中。
>>> who = 'knights'
>>> what = 'Ni!'
>>> print 'We are the',who,'who say',what,what,what,what
We are the knights who say Ni! Ni! Ni! Ni!
>>> print "We are the %s who say %s" %(who,((what + " ")*4))
We are the knights who say Ni! Ni! Ni! Ni!
>>>
########>>> for number in range(14):
... print number
...
0
1
2
3
4
5
6
7
8
9
10
11
12
13
>>> zimu = 'abcdefg'
>>> for z in zimu:
... print z
...
a
b
c
d
e
f
g
还可以和len()搭配使用>>> zimu = 'abcdefg'
>>> for i in range(len(zimu)): #显示字符串编号
... print zimu[i],'%d'%(i)
...
a 0
b 1
c 2
d 3
e 4
f 5
g 6
>>>
>>> for i, ch in enumerate(zimu):#####enumerate()函数 同时输出字母和编号
... print ch ,'(%d)' % i
...
a (0)
b (1)
c (2)
d (3)
e (4)
f (5)
g (6)
>>>
#####列表解析
>>> squared = [x ** 2 for x in range(4)]
>>> print squared
[0, 1, 4, 9]
>>>
>>> squared = [x ** 2 for x in range(4)]
>>> for i in squared:
... print i
...
0
1
4
9