python核心编程-第六章-我的笔记(一)

0.    序列包括字符串、列表和元组三种类型git

1.    序列web

1.0  序列的每个元素能够经过指定一个偏移量的方式获得,多个元素能够经过切片操做的方式一次获得。偏移量从0开始,到总元素数-1结束算法

1.1  标准类型操做符数据库

标准类型操做符通常适用于全部的序列类型api

1.2  序列类型操做符服务器

1.2.1  成员关系操做符—in和not in网络

 成员关系操做符用来判断一个元素是否属于一个序列,返回True/False:知足成员关系就返回True,不然返回False。app

>>> "12" in "123456"
True
>>> "12" not in "13456"
True

1.2.2  链接操做符框架

链接操做符能够链接一个序列和另外一个类型相同的序列。ide

>>> "123" + "456"
'123456'

须要注意:①链接、合并字符串,更有效的办法是把全部子字符串放到一个列表或可迭代对象中,再调用join方法;相似的,合并列表,更有效的办法是调用列表的extend()方法。

>>> str1 = 'abc'
>>> str2 = 'def'
>>> ' '.join((str1, str2))
'abc def'
abc def
>>> list1 = list(str1)
>>> list2 = list(str2)
>>> list1.extend(list2)
>>> list1
['a', 'b', 'c', 'd', 'e', 'f']

②当仅须要简单的合并两个对象的内容,或者链接那些没有返回值(返回None)的时候,链接操做符较为简便

1.2.3  重复操做符

重复操做符返回一个新的、包含多份原对象拷贝的对象,用于须要一个序列的多份拷贝时,如例:

>>> "12" * 3
"121212"
>>> [12,13] * 3
[12,13,12,13,12,13]

重复操做符链接的非列表对象必须是整型,不能是长整型

1.2.4  切片操做符

①用方括号[]加下标能够访问序列的每个元素;方括号[]中用冒号:把开始下标和结束下标分开能够访问序列的一组元素,这种访问序列的方式就叫作切片

②访问单个元素

语法:sequence[index]

index能够是正数也能够是负数,区别在于正数从序列的开始为起点,负数从序列的结束为起点,故index为正数时范围是0<=index<=len(sequence)-1;负数范围是-len(sequence)<=index<=-1

sequence[len(sequence)-1] = sequence[-1]    sequence[0] = sequence[-len(sequence)]

③访问一组元素

当给出用冒号分割的开始和结束索引值时,能够访问一组元素。

语法:sequence[start_index:end_index]

起始索引和结束索引都是可选的,若是没有提供或者用None做为参数,则从序列的开始处开始,或者到序列的最后结束

1.2.5  切片扩展

序列切片的第三个可选操做是选择步长

语法  sequence[start_index:end_index:step]

如:

>>> a = [1,2,3,4,5,6]
>>> a[::-1]
[6,5,4,3,2,1]    #翻转操做
>>> a[::2]
[1,3,5]      #隔一个取一个

 1.2.6  切片索引

切片索引语法灵活,即便开始和结束的索引值超过字符串的长度也不要紧。

例子①  对一个字符串,经过循环每次把位于最后的一个字符砍掉,下面是一种实现方法

s = 'abcdefg'
i = -1
for i in range(-1,-len(s),-1):
    print s[:i]

②若需在第一次迭代时显示整个字符串,则可以下修改

s = 'abcdefg'
i = -1
for i in [None] + range(-1,-len(s),-1):
    print s[:i]

1.3  内建函数

1.3.1  类型转换

list()  把可迭代类型转换为列表:

>>> list("123456")
['1','2','3','4','5','6']

str()  把对象转换成字符串

>>> str(123)
'123'
>>> str([1,2,3])
'[1,2,3]'

str()在输出对象的可打印信息时颇有用;

list()和tuple()函数在用于列表和元组的互换时颇有用

转换类型函数说明:

1.3.2  可操做

 Python为序列类型提供的内建可操做函数包括如下各类,其中len();  reversed();  sum()函数只能接受序列类型做为参数。剩下的能够做为可迭代对象做为参数。max()、min()函数还能够接受一个参数列表

2.字符串和操做符

2.1  标准类型操做符

字符串作比较操做时,字符串是按照ASCII码值比较的

2.2  序列操做符切片

①正向索引范围从0到len()-1;反向索引范围从-1到-len()

2.3  成员操做符 in / not in

①成员操做符用于判断一个字符和字符串是否出如今另外一个字符串中,出现返回True,不然返回False

>>> 'ab' in 'abc'
True
>>> 'ab' in 'bcde'
False
>>> 'ab' not in 'abc'
False
>>> 'ab' not in 'bcde'
True

②string模块中预约义的方法

>>> import string
>>> string.uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.lowercase
'abcdefghijklmnopqrstuvwxyz'
>>> string.letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.digits
'0123456789'

标识符检查例子(idcheck.py)

import string

alphas = string.letters + '_'
nums = string.digits

print "Welcome to the Identifier Checker v1.0"
print "Testees must be at least 2 chars long."
myInput = raw_input("Identifier to test? ")

if len(myInput) < 2:
    print "Testees must be at least 2 chars long!"

elif len(myInput) >= 2:
    
    if myInput[0] not in alphas:
        print '''invalid: first symbol must be
            alphabetic'''
            
    else:
        for otherChar in myInput[1:]:
        
            if otherChar not in alphas + nums:
                print '''invalid: remaining
                    symbol must be alphabetic'''
                break
        else:
            print "Okay as an identifier"

注①:这里用到了for-else结构。for遍历循环能够有可选的一个else分支语句,在循环迭代正常完成后执行,即除非以正常方式结束循环,不然其余任意方式(如break)退出循环时,else分支不会被执行。看下面的例子

>>> for i in range(5):
...     print i
... else:
...     print "This will print."
...
0
1
2
3
4
This will print
>>>
>>> for i in range(5):
...     if i >= 3:
...         break
...     print i
... else:
...     print "This will not print."
...
0
1
2
>>>

注②通常来讲,从性能的角度来考虑,重复操做做为参数在循环体里面是很低效的 因此咱们能够对例子里的某段代码作出修改

# 原代码
# for otherChar in myInput[1:]:    
#     if otherChar not in alphas + nums:
#         pass

# 修改后代码
alphasnums = alphas + nums

for otherChar in myInput[1:]:
    if otherChar not in alphasnums"
        pass

2.4  链接符 "+"

字符串的upper() lower() 方法

>>> Upp = 'ABC'
>>> Low = 'abc'
>>> Upp.lower()
'abc'
>>> Low.upper()
'ABC'

3.  只适用于字符串的操做符

3.1  格式化操做符(%)  格式化字符串

3.1.1  字符串格式化符号

A.字符串格式化的符号

B.格式化操做符辅助指令

 

Python支持两种格式的输入参数,一种是元组形式,一种是字典形式。

元组形式的例子:

>>> "%x" % 108
'6c'
>>> "%X" % 108
'6C'
>>> "%#X" % 108    # 八进制数前显示'0',十六进制前面显示'0x'或'0X'
'0X6C'
>>> "%#x" % 108    # x输出小写,X输出大写
'0x6c'
>>> '%f' % 1234.567890
'1234.567890'
>>> '%.2f' % 1234.567890    # 小数点后保留两位
'1234.57'
>>> '%08.2f' % 1234.567890  # 小数点后保留2位,且最小显示宽度为8,小数点算一位,不足8位用0补充
'01234.57'
>>> '%8.2f' % 1234.567890   # 小树点后保留2为,且最小宽度为8,小数点算一位,不足8位空格补充
' 1234.57'
>>> '%g' % 1234.567890
'1234.57'    # %g会根据值得大小选择%e或%f控制输出,且输出最多保留6位有效数字
>>> '%g' % 1.234567890
'1.23457'
>>> '%g' % 12345678.9
'1.23457e+07'
>>> '%e' % (111111111111L)
'1.111111e+11'

字典形式的例子:

>>> 'There are %(howmany)d %(lang)s Quotation Symbols' % {'lang': 'Python', 'howmany': 3}
'There are 3 Python Quotation Symbols'

3.2  字符串模版:更简单的替代品

新式的字符串Template对象能够替代字典形式的字符串格式化,有两个方法:substitute()和safe_substitute()。前者更加严谨,缺乏key时报错;后者缺乏对应的key则会原封不动的显示出来。

>>> from string import Template
>>> s = Template('There are ${howmany} ${long} Quotation Symbols')
>>> 
>>> print s.substitute(lang='Python', howmany=3)
There are 3 Python Quotation Symbols
>>> print s.safe_substitute(lang='Python')
There are ${howmany} Python Quotation Symbols

3.3  原始字符串操做符

在字符串引号前加r或R,则对字符串中的转义字符默认不处理

>>> print '\n'


>>> print r'\n'
\n

3.4  内建函数

3.4.1  序列类型函数

len()  max()  min()  enumerate()    zip()函数均适用于字符串

>>> str1 = 'abc'
>>> len(str1)
3
>>> str2 = 'lmn'
>>> str3 = 'xyz'
>>> max(str2)
'n'
>>> min(str3)
'x'
>>> s = 'Python'
>>> for i, t in enumerate(s):
...     print i, t
...
0 P
1 y
2 t
3 h
4 o
5 n
>>> s, t = 'Pyt', 'hon'
>>> zip(s,t)
[('P', 'h'), ('y', 'o'), ('t', 'n')]

3.5  字符串内建方法

字符串内建方法可参考下列表

下面是一些例子

>>> quest = 'what is your favorite color?'
>>> quest.capitalize()
'What is your favorite color?'      
>>>
>>> quest.center(40)
'      What is your favorite color?      '
>>>
>>> quest.count('or')
2
>>>
>>> quest.endswith('or')
False
>>> quest.endswith('or?')
True
>>>
>>> quest.find('or')
16
>>> quest.find('ro')
-1
>>> quest.find('or',18)
25
>>>
>>> quest.index('or',0,18)
16
>>>
>>> alnum = 'abc123'
>>> notalnum = 'abc 123'
>>> alpha = 'abc'
>>> num = '123'
>>> num_hex = '017'
>>> num_oct = '0X17'
>>> alnum.isalnum()
True
>>> notalnum.isalnum()
False
>>> alpha.isalpha()
True
>>> alnum.isalpha()
False
>>> u'123'.isdecimal()
True
>>> u'0X17'.isdecimal()
False
>>> alpha.isdigit()
False
>>> num.isdigit()
True 
>>> quest.islower()
True 
>>> quest.capitalize().islower()
False
>>> quest.isspace()
False
>>> '  '.isspace()
True
>>> quest.istitle()
False
>>> quest.title().istitle()
True
>>> quest.isupper()
False
>>> quest.upper().isupper()
True
>>> ':'.join(quest.split())
'what:is:your:favorite:color?'
>>> quest.ljust(40)
'what is your favorite color?            '
>>> '   abc'.lstrip()
'abc'
>>> quest.partition('or')
('what is your fav', 'or', 'ite color?')
>>> quest.split('or')
['what is your fav', 'ite col', '?']
>>> quest.replace('or', 'OR')
'what is your favORite colOR?'
>>> 
>>> quest.rjust(40)
'            what is your favorite color?'

3.6 字符串的独特特性

3.6.1  特殊字符串和控制字符

①一个反斜线"\"加一个单一字符能够表示一个特殊字符,一般是一个不可打印的字符,这就是转义的功能

②转义字符表

③单独的反斜线做为连字符,将本行和下一行的内容链接起来

>>> print "This a \
... sentence \
... and \
... this."
This is a sentence and this.

3.6.2  三引号

①Python的三引号容许一个字符串跨多行,字符串中能够包含换行符、制表符以及其余特殊字符

3.7  编码问题

3.7.1  raw_input在Windows系统的命令后模式下偶有中文提示语言乱码问题,缘由在于Windows的CMD输出的编码问题,以下操做便可

>>> # -*- coding:utf-8 -*-
>>> print u'中文测试'
中文测试
>>> raw_input(u'中文测试'.encode('gbk'))
中文测试_

3.7.2  一个例子

'''
An example of reading and writing Unicode strings:Writes
a Unicode string to file in utf-8 and reads it back in.
'''
CODEC = 'utf-8'
FILE = 'Unicode.txt'

hello_out = u"Hello world\n"
bytes_out = hello_out.encode(CODEC)
f = open(FILE, 'w')
f.write(bytes_out)
f.close()

f = open(FILE, 'r')
bytes_in = f.read()
f.close()
hello_in = bytes_in.decode(CODEC)
print hello_in,

3.7.3  实际应用中的建议

    ①程序中出现字符串是在前面加前缀"u"

    ②用unicode()代替str()函数

    ③非必要时不要编解码Unicode字符。只有在写入文件/数据库/网络时才调用encode()函数;相应的,须要把数据读取回来时才使用decode()函数

    ④Python标准库里面大部分模块都支持Unicode,但pickle模块不支持,因此最好避免基于文本的pickle操做

    ⑤假设构建一个用数据库来读写Unicode数据的web应用,为了支持Unicode,必须确保如下方面对Unicode的支持:

            A.数据库服务器(MySQL等)

            B.数据库适配器

            C.web开发框架            

3.8  相关模块

下表列出了Python标准库里面与字符串有关的模块

3.9  列表

①更新列表能够经过在等号左边指定一个索引或一个索引范围,也能够经过append()方法

>>> a_list = [123, 456, 789, 'abc', 'def']
>>> a_list[2] = 'hhh'
>>> a_list
[123, 456, 'hhh', 'abc', 'def']
>>> a_list.append('I am the new')
>>> a_list
[123, 456, 'hhh', 'abc', 'def', 'I am the new']

②删除列表中的元素,能够用del语句和remove方法及pop方法,经过例子来看不一样

>>> a_list
[123, 456, 'hhh', 'abc', 'def', 'I am the new']
>>> del a_list[2]
>>> a_list
[123, 456, 'abc', 'def', 'I am the new']
>>> a_list.remove(123)
>>> a_list
[456, 'abc', 'def', 'I am the new']
>>> a_list.pop()
>>> a_list
[456, 'abc', 'def']
>>> a_list.pop(1)
[456, 'def']

3.10  操做符和内建函数

3.10.1  标准类型操做符

标准类型操做符比较两个列表时,两个列表的每一个元素分别比较,直到有一方的元素胜出为止。

3.10.2  列表类型操做符和列表解析

列表解析结合了列表的方括弧和for循环

>>> [i ** 3 for i in [8, -2, 5]]
[512, -8, 125]
>>> [i * 3 for i in 'abcde']
['aaa', 'bbb', 'ccc', 'ddd', 'eee']

3.10.3  cmp()函数比较

cmp()比较两个列表的算法以下:

    ①对两个列表的每一个元素逐一进行比较

    ②若是比较的元素是同类型的,则比较其值并返回结果

    ③若不是同一类型,则检查他们是不是数字:

        A。若是是数字,则进行必要的强制类型转换,而后比较

        B。若是只有一方的元素是数字,则另外一方的元素"大"(数字是"最小的")

        C。不然,经过类型名字的字母顺序进行比较

    ④若是有一个列表首先达到末尾,则另外一个长一点的元素大

    ⑤若是两个列表都达到末尾且全部元素都相等,则返回0即断定两个列表相等

3.10.4  序列类型函数

    ①len()函数返回列表或元组元素个数,每一个对象都做为一项来处理

    ②max()和min()返回列表或元组各元素中最大或最小的项

    ③函数reversed()对列表或词典进行翻转;sorted()对列表排序

>>> s = ['They', 'stamp', 'them', 'when', "They're", 'small']
>>> for t in reversed(s):
...     print t,
...
small They're when them stamp They
>>> sorted(s)
['They', "They're", 'small', 'stamp', 'them', 'when']

    ④enumerate()和zip()

>>> albums = ['tales', 'robot', 'pyramid']
>>> for i, album in enumerate(albums):
...     print i, album
...
0 tales
1 robot
2 pyramid
>>> fn = ['ian', 'stuart', 'david']
>>> ln = ['bairnson', 'elliott', 'paton']
>>>
>>> for i, j in zip(fn, ln):
...     print ('%s %s' % (i, j)).title() 
...
Ian Bairnson
Stuart Elliott
David Paton

    ⑤sum()

>>> a = [12, 3, 4]
>>> sum(a)
19
>>> sum(a, 1)
20
>>> import operator
>>> reduce(operator.mul, a)
144

    注:reduce()是内建函数,接收的第一个参数是一个二元操做函数,接受的第二个参数是一个列表或元组,先对列表或元组中的第1和第2个元素利用给定函数进行操做,获得的结果再与第3个元素利用给定函数计算,最终获得一个结果。

3.11  列表的内建方法

    3.11.1  列表内建方法表

下面是使用这些方法的例子

>>> music_media = [45]
>>> music_media
[45]
>>> music_media.append('long playing record')
>>> music_media
[45, 'long playing record']
>>> music_media.count(45)
1
>>> music_media.count('Hello')
0
>>> music_media.extend(['Hello'])
>>> music_media
[45, 'long playing record', 'Hello']
>>> music_media.index(45)
0
>>> music_media.index('H')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: 'H' is not in list 
>>> music_media.insert(1, 46)
>>> music_media
[45, 46, 'long playing record', 'Hello']
>>> music_media.pop(1)
46
>>> music_media
[45, 'long playing record', 'Hello']  
>>> music_media.remove(45)
>>> music_media
['long playing record', 'Hello']
>>> music_media.reverse()
>>> music_media
['Hello', 'long playing record']
>>> music_media.extend('Hello')
>>> music_media.sort()
>>> music_media
['H', 'Hello', 'e', 'l', 'l', 'long playing record', 'o']
相关文章
相关标签/搜索