字符串
序列
序列类型操作符
序列操作符 | 作用 |
seq[ind] | 获得下标为ind的元素 |
seq[ind1:ind2] | 获得下标从ind1到ind2间的元素结合 |
seq * expr | 序列重复expr次 |
seq1 + seq2 | 连接序列seq1和seq2 |
obj in seq | 判断obj元素是否包含在seq中 |
obj not in seq | 判断obj元素是否不包含在seq中 |
内建函数
函数 | 含义 |
list(iter) | 把可迭代对象转换为列表 |
str(obj) | 把obj对象转换成字符串 |
tuple(iter) | 把一个可迭代对象转换成一个元组对象 |
>>> list('hello') ['h', 'e', 'l', 'l', 'o'] >>> list(['hello','world']) ['hello', 'world'] >>> str(['hello,','world']) "['hello,', 'world']"
len(seq):返回seq的长度
max(iter,key=None):返回iter中的最大值
>>> max('abf') 'f' >>> ord('a') 97 >>> ord('f') 102 >>> max([10,234,3421,12]) 3421
enumerate:接受一个可迭代对象作为参数,返回一个enumerate对象
>>> for i,j in enumerate(aList): ... print "index %d:%s" %(i,j) ... index 0:hello index 1:world
reversed(seq):接受一个序列作为参数,返回一个以逆序访问的迭代器
sorted(iter):接受一个可迭代对象作为参数,返回一个有序的列表
>>> aList = [32,43,323,55] >>> sorted(aList) [32, 43, 55, 323] >>> for item in reversed(aList): ... print item ... 55 323 43 32
字符串
字符串操作符
比较操作符:字符串大小按ASCII码值大小进行比较
切片操作符:[]、[:]、[::]
成员关系操作符:in、not in
>>> pyStr = 'Hello World!' >>> pyStr[::2] 'HloWrd' >>> pyStr[::-1] '!dlroW olleH'
小练习:检查标识符
1、程序接受用户输入
3、判断用户输入的标识符是否合法
#!/usr/bin/env python import string first_chs = string.letters + '_' other_chs = first_chs + string.digits def check_id(myid): if myid[0] not in first_chs: print "1st char invalid." return for ind,ch in enumerate(myid[1:]): if ch not in other_chs: print "char in position: %s invalid" %(ind + 2) break else: print "%s is valid" % myid if __name__ == '__main__': myid = raw_input("id to check: ") if myid: check_id(myid) else: print "You must input an identifier."
格式化操作符
字符串可以使用格式化符号来表示特定含义
格式化字符 | 转换方式 |
%c | 转换成字符 |
%s | 优先用str()函数进行字符串转换 |
%d/%i | 转成有符号十进制数 |
%o | 转成无符号八进制数 |
%e/%E | 转成科学计数法 |
%f/%F | 转成浮点数 |
>>> "%o" % 10 '12' >>> "%#o" % 10 '012' >>> "%#x" % 10 '0xa' >>> "%e" % 1000000 '1.000000e+06'
>>> "%f" % 3.1415 '3.141500' >>> "%4.2f" % 3.1415 '3.14'
格式化操作符辅助指令 | 作用 |
* | 定义宽度或小数点精度 (>>> "%*s%*s" % (-8,'name',-5,'age') 'name age ' |
- | 左对齐 |
+ | 在正数前面显示加号 |
<sp> | 在正数前面显示空格 |
# | 在八进制数前面显示0,在十六进制数前面显示‘0 x’或者‘0X ’ |
0 | 显示的数字前面填充0而不是默认的空格 |
>>> "my ip is: %s" % '192.168.1.1' 'my ip is: 192.168.1.1' >>> "my ip is: {}".format('192.168.1.1') 'my ip is: 192.168.1.1' >>> "my ip is:{},you ip is: {}".format('192.1268.1.1','172.40.1.1') 'my ip is:192.1268.1.1,you ip is: 172.40.1.1' >>> "my ip is:{1},you ip is: {0}".format('192.1268.1.1','172.40.1.1') 'my ip is:172.40.1.1,you ip is: 192.1268.1.1'小练习
1、提示用户输入(多行)数据
2、假定屏幕宽度为50,用户输入的多行数据显示(文本内容居中):
+********************************+
+ hello world +
+ great work! +
+********************************+#!/usr/bin/env pythondef get_contents(): contents = [] while True: data = raw_input("(Enter to quit)> ") if not data: break contents.append(data) return contentsif __name__ == '__main__': width = 48 lines = get_contents() print'+%s+' %('*' * width) for line in lines: sp_wid,extra = divmod((width - len(line)),2) print "+%s%s%s+" %(' ' * sp_wid,line,' ' * (sp_wid + extra)) print'+%s+' % ('*' * width)
字符串模板
string 模板提供了一个Template对象,利用该对象可以实现字符串模板的功能
>>> import tab >>> import string >>> origTxt = "Hi ${name}, I will see you ${day}" >>> t = string.Template(origTxt) >>> t.substitute(name = 'bob',day = 'tomorrow') 'Hi bob, I will see you tomorrow' >>> t.substitute(name = 'tom',day = 'the day after tommorrow') 'Hi tom, I will see you the day after tommorrow'
小练习创建用户
1、编写一个程序,实现创建用户的功能
2、提示用户输入用户名
3、随机生成8位密码
4、创建用户并设置密码
5、发邮件通知用户相关信息
#!/usr/bin/env pythonimport sysimport osimport randpass2import stringcontents = '''username: ${username}password: ${password}'''t = string.Template(contents)def adduser(user, passwd, email): os.system("useradd %s" %user) os.system("echo %s:%s | chpasswd" %(passwd,user)) #os.system("echo %s | passwd --stdin %s" %(passwd,user)) data = t.substitute(username=user,password = passwd) os.system("echo -e '%s' | mail -s 'user info' %s" %(data,email))if __name__ == '__main__': username = sys.argv[1] pwd = randpass2.gen_pass() adduser(username,pwd,"root@localhost")
原始字符串操作符
原始字符串操作符是为了对付那些在字符串中出现的特殊字符
在原始字符串里,所有的的字符都是直接按照字面的意思来使用,没有转义特殊或不能打印的字符
>>> winPath = "c:\windows\temp" >>> winPath 'c:\\windows\temp' >>> import tab >>> print winPath c:\windows emp >>> newPath = r"c:\windows\temp" >>> newPath 'c:\\windows\\temp' >>> print newPath c:\windows\temp 内建函数
string.cpaitalize():把字符串的第一个字符大写
>>> 'hello world!'.capitalize() 'Hello world!'
string.center(width):返回一个原字符串居中,并使用空格填充至长度width的新字符串
>>> print '|'+ 'hello world!'.center(20)+ '|' | hello world! |
>>> hi = "hello wolrd"
>>> hi.center(20,'+') '++++hello wolrd+++++' >>> hi.ljust(20,'+') 'hello wolrd+++++++++' >>> hi.rjust(20,'+') '+++++++++hello wolrd'
string.count(str,beg=0,end=len(string)):返回str在string里面出现的次数,如果beg或者end指定则返回指定范围内str出现的次数
>>> hi = "hello wolrd"
>>> hi.count("l")
3
string.endswith(obj,beg=0,end=len(string)):检查字符串是否以obj结束,如果beg或者end指定检查指定范围内是否以obj结束,如果是,返回True,否则返回False
>>> hi.endswith("d") 是 以d结尾? True >>> hi.startswith("hello") 是以hello 开始? True
>>> '12'.isdigit() 是数字 True >>> hi.islower() 是小写 True>>> hi.isupper() 是大写? False
>>> hi.isalpha() False >>> "hello".isalpha() True >>> "hello123".isalpha()是不是字母 False
>>> "hello123".isalnum()是不是字母数字组合 True string.strip():删除string字符串两端的(空白)
strint.upper():转换string中的小写字母为大写
>>> hi = 'hello wolrd!' >>> hi.strip('!') 'hello wolrd'
>>> "\t hello world\n".strip() 'hello world' >>> "\t hello world\n".lstrip() 'hello world\n' >>> "\t hello world\n".rstrip() '\t hello world' >>> 'hello'.upper() 'HELLO' >>> 'hello'.lower() 'hello'
string.split(str="",num = string.count(str)):以str为分隔符切片string,如果num有指定值,则仅分隔num个字符串>>> 'mytest.tar.gz'.split('.') ['mytest', 'tar', 'gz']
>>> testStr = ''' hello everyone. ... welcome to python. ... it is a great language.''' >>> testStr ' hello everyone.\nwelcome to python.\nit is a great language.' >>> print testStr hello everyone. welcome to python. it is a great language. >>> testStr.splitlines() [' hello everyone.', 'welcome to python.', 'it is a great language.'] >>> >>> mylist = ['mytest', 'tar', 'gz'] >>> '.'.join(mylist) #拼接 'mytest.tar.gz'
>>> '/'.join(mylist) 'mytest/tar/gz' >>> hi 'hello wolrd!' >>> hi.replace('l','a') 'heaao woard!' >>> hi.replace('l','a',2) 'heaao wolrd!'列表
列表基础操作
创建及访问列表
列表是有序、可变的数据类型
列表中可以包含不同类型的对象
列表可以有[]或工厂函数创建
支持下标及切片操作
>>> aList = [1,2,'hello'] >>> bList = list('new') >>> print aList [1, 2, 'hello'] >>> print bList ['n', 'e', 'w']
更新列表
通过下标只能更新值,不能使用下标添加新值
>>> alist = [10,20] >>> alist[0] = 1 >>> alist [1, 20]
>>> alist[2]=30 Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: list assignment index out of range >>> alist = [10,20,30,40] >>> alist[1:3] [20, 30] >>> alist[1:3] = [2,3] >>> alist [10, 2, 3, 40]
>>> alist[1:3] = [20,30,35] >>> alist [10, 20, 30, 35, 40]>>> alist[2:2] = [22,24,26,28] >>> alist [10, 20, 22, 24, 26, 28, 30, 35, 40]
可以使用append方法追加新值
删除列表
可以使用del删除列表项或整个列表
删除列表项还可以使用pop()及remove()方法
>>> aList = ['hello','world','new','list','name'] >>> aList.pop() #弹出列表中最后一个值(默认下标为-1),下标可在()中显示标出 'name' >>> aList ['hello', 'world', 'new', 'list'] >>> del aList[2] >>> aList ['hello', 'world', 'list'] >>> aList.remove('list') #删除指定元素,非下标,若有多个,则只删除第一个 >>> aList ['hello', 'world'] >>> del aList >>> print aList Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'aList' is not defined
列表操作进阶
列表操作符
由于列表也是序列里诶型,所以+、*、in、not in都适用与列表,但是需要注意参与运算的对象属于同一类型
>>> ['hello','world'] * 2 ['hello', 'world', 'hello', 'world'] >>> ['hello','world'] + 'new' Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: can only concatenate list (not "str") to list >>> ['hello','world'] + ['new'] ['hello', 'world', 'new']
作用于列表的函数
与字符串类似,列表也支持如下函数:
- len()
- max()
- min()
- sorted()
- enumerate()
- sum()
- zip()
列表内建函数
列表方法 | 操作 |
list.append(obj) | 向列表中添加一个对象obj |
list.count(obj) | 返回一个对象obj在列表中出现的次数 |
list.extend(seq) | 把序列seq的内容添加到列表中 |
list.index(obj) | 返回obj对象的下标 |
list.insert(index,obj) | 在索引量为index的位置插入对象obj |
list.reverse() | 原地翻转列表 |
list.sort() | 排序 |
>>> alist [10, 20, 22, 24, 26, 28, 30, 35, 40] >>> alist.append('hi') >>> alist [10, 20, 22, 24, 26, 28, 30, 35, 40, 'hi'] >>> alist.extend('hi') >>> alist [10, 20, 22, 24, 26, 28, 30, 35, 40, 'hi', 'h', 'i']
>>> alist.extend(['hello','world']) >>> alist [10, 20, 22, 24, 26, 28, 30, 35, 40, 'hi', 'h', 'i', 'hello', 'world']
>>> alist[-5:] ['hi', 'h', 'i', 'hello', 'world'] >>> alist[-5:] = [] >>> alist [10, 20, 22, 24, 26, 28, 30, 35, 40] >>> alist.index(24) 3 >>> alist.insert(3,30) >>> alist [10, 20, 22, 30, 24, 26, 28, 30, 35, 40] >>> alist.reverse() >>> alist [40, 35, 30, 28, 26, 24, 30, 22, 20, 10] >>> alist.sort() >>> alist [10, 20, 22, 24, 26, 28, 30, 30, 35, 40] >>> import random >>> random.shuffle(alist) # 将alist 列表顺序打乱 >>> alist [30, 20, 30, 22, 26, 35, 28, 10, 40, 24]小练习(答案见评论)
1、栈是一个后进先出的结构
2、编写一个程序,用列表实现栈结构
3、需要支持压栈、出栈、查询功能
元组
元组基础
创建元组
通过()或工厂函数tuple()创建元组
元组是有序的、不可变类型
与列表类似,作用于列表的操作,绝大多数也可以作用于元组
>>> aTuple = ('one','two','Three') >>> bTuple = tuple(['hello','world']) >>> print aTuple ('one', 'two', 'Three') >>> print bTuple ('hello', 'world')
元组操作符
由于元组也是序列类型、所以作用在序列上的操作都可以用于元组
通过in、not in 判断成员关系
>>> print bTuple ('hello', 'world') >>> 'hello' in bTuple True
元组特性
单元素元组
如果一个元组中只有一个元素,那么创建该元素的时候需要加上一个逗号
>>> cTuple = ("hello") >>> print cTuple hello >>> type(cTuple) <type 'str'> >>> dTuple = ('hello',) >>> print dTuple ('hello',) >>> type(dTuple) <type 'tuple'>
“更新”元组
虽然元组本身是不可变的,但是因为它同时属于容器类型,也就意味着元组的某一个元素是可变的容器类型,那么这个元素中的项目仍然可变
>>> aTuple = ('bob',['bob@tarena.com','beijing']) >>> print aTuple ('bob', ['bob@tarena.com', 'beijing']) >>> aTuple[0] = 'tom' Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object does not support item assignment >>> aTuple[1][1] = 'shanghai' >>> print aTuple ('bob', ['bob@tarena.com', 'shanghai'])