字符串:
- 一个个字符组成的有序的序列,是字符的集合
- 使用单引号、双引号、三引号引住的字符序列
- 字符串是不可变对象
- Python3起,字符串就是Unicode类型
1 >>> a = 'ab' + 'c'+ 'd' 2 >>> type(a) 3 <class 'str'> 4 >>> id(a) 5 12128640 6 >>> a = 'ab' + 'c'+ 'd'+ 'e' 7 >>> id(a) 8 12128672 9 # 内存分配的空间不一样 10 >>> a 11 'abcde' 12 >>> a[1] 13 'b' 14 >>> a[1] = l 15 Traceback (most recent call last): 16 File "<stdin>", line 1, in <module> 17 NameError: name 'l' is not defined 18 # 和列表一样的用法,也是不可改变
字符串的定义和初始化
1 s1 = 'string' 2 print(s1) 3 string 4 ############################## 5 s2 = "string2" 6 print(s2) 7 string2 8 ############################## 9 s3 = '''this's a "String"''' 10 print(s3) 11 this's a "String" 12 ############################## 13 s4 = 'hello \n magedu.com' 14 print(s4) 15 hello 16 magedu.com 17 ############################## 18 s5 = r"hello \n magedu.com" 19 print(s5) 20 hello \n magedu.com 21 ############################## 22 s6 = 'c:\windows\nt' 23 print(s6) 24 c:\windows 25 t 26 ############################## 27 s7 = R"c:\windows\nt" 28 print(s7) 29 c:\windows\nt 30 ############################## 31 s8 = 'c:\windows\\nt' 32 print(s8) 33 c:\windows\nt 34 ############################## 35 sql = """select * from user where name='tom'""" 36 print(sql) 37 select * from user where name='tom' 38 39 # 注意各种标点和转义符
字符串元素访问
- 字符串支持使用索引访问
1 sql = """select * from user where name='tom'""" 2 print(sql[4]) 3 sql[4] = 'o' 4 print(sql[4]) 5 ####################################### 6 c 7 # 这里返回的是字符串'c',而不是字符c 8 sql[4] = 'o' 9 TypeError: 'str' object does not support item assignment 10 # 这里注意不可进行修改
- 有序的字符集合,字符序列
1 sql = """select * from user where name='tom'""" 2 for c in sql: 3 print(c,end=' ') 4 print() 5 print(type(c)) 6 ##################################### 7 s e l e c t * f r o m u s e r w h e r e n a m e = ' t o m ' 8 <class 'str'>
- 可迭代
1 sql = """select * from user where name='tom'""" 2 lst = list(sql) 3 print(lst) 4 t = tuple(sql) 5 print(t) 6 ####################################### 7 ['s', 'e', 'l', 'e', 'c', 't', ' ', '*', ' ', 'f', 'r', 'o', 'm', ' ', 'u', 's', 'e', 'r', ' ', 'w', 'h', 'e', 'r', 'e', ' ', 'n', 'a', 'm', 'e', '=', "'", 't', 'o', 'm', "'"] 8 ('s', 'e', 'l', 'e', 'c', 't', ' ', '*', ' ', 'f', 'r', 'o', 'm', ' ', 'u', 's', 'e', 'r', ' ', 'w', 'h', 'e', 'r', 'e', ' ', 'n', 'a', 'm', 'e', '=', "'", 't', 'o', 'm', "'")
字符串连接
- +连接,a=‘a’,a=‘a’+'b',a='ab',将两个字符串连接在一起,返回一个新字符串
- join连接,“string”.join(iterable) -> str
- 将可迭代对象连接起来,使用string作为分隔符
- 可迭代对象本身元素都是字符串
- 返回一个新字符串
1 a = 'abcd' 2 b = ' '.join(a) 3 print(b) 4 a b c d 5 ################### 6 c = "@".join(a) 7 print(c) 8 a@b@c@d 9 ################### 10 lst = ['1','2','3'] 11 print(' '.join(lst)) 12 1 2 3 13 ################### 14 print("\n".join(lst)) 15 1 16 2 17 3 18 ################### 19 lst1 = ['1',['a','b'],'3'] 20 print(' '.join(lst1)) 21 Traceback (most recent call last): 22 File "D:/untitled/project2/day1/zifuchuan.py", line 2, in <module> 23 print(' '.join(lst1)) 24 TypeError: sequence item 1: expected str instance, list foun 25 # 这种嵌套类型的会报错
字符串分割
- split系
- 将字符串按照分隔符分割成若干字符串,并返回列表
- split(sep=None,maxsplit=-1) -> list of strings
- 从左到右
- sep指定分割字符串,缺省的情况下空白字符串作为分隔符
- maxsplit指定分割的次数,-1表示遍历整个字符串
1 >>> s1 = "I'm \ta super student." 2 3 >>> s1.split() 4 ["I'm", 'a', 'super', 'student.'] 5 6 >>> s1.split('s') 7 ["I'm \ta ", 'uper ', 'tudent.'] 8 9 >>> s1.split('super') 10 ["I'm \ta ", ' student.'] 11 12 >>> s1.split(' ') 13 ["I'm", '\ta', 'super', 'student.'] 14 15 >>> s1.split(' ',2) 16 ["I'm", '\ta', 'super student.'] 17 18 >>> s1.split('\t',2) 19 ["I'm ", 'a super student.']
- resplit()是相反的效果。
- 从右到左,其余的参考split()
- splitlines([keepends]) -> list of strings
- 按照行来切分字符串
- keepends指的是是否保留行分隔符
- 行分隔符包括\n、\r\n、\r等
1 >>> 'ab c\n\nde fg\rk|\r\n'.splitlines() 2 ['ab c', '', 'de fg', 'k|'] 3 # 行分隔符包括\n、\r\n、\r等等 4 5 >>> 'ab c\n\nde fg\rk|\r\n'.splitlines(True) 6 ['ab c\n', '\n', 'de fg\r', 'k|\r\n'] 7 #True保留行分隔符 8 9 >>> s1 = '''I'm a super student.You're a super teacher.''' 10 >>> print(s1) 11 I'm a super student.You're a super teacher. 12 13 >>> print(s1.splitlines()) 14 ["I'm a super student.You're a super teacher."] 15 16 >>> print(s1.splitlines(True)) 17 ["I'm a super student.You're a super teacher."]
- partition系
- 将字符串按照分隔符分割成2段,返回这2段和分隔符的元组
- partition(sep) -> (head,sep,tail)
- 从左到右,遇到分隔符就把字符串分割成两部分,返回头、分隔符、尾三部分的三元组;如果没有找到分隔符,就返回头、2个空元素的三元组
- sep分割字符串,必须指定
1 >>> s1 = "I'm a super student." 2 >>> s1.partition('s') 3 ("I'm a ", 's', 'uper student.') 4 5 >>> s1.partition('stu') 6 ("I'm a super ", 'stu', 'dent.') 7 8 >>> s1.partition('') 9 Traceback (most recent call last): 10 File "<stdin>", line 1, in <module> 11 ValueError: empty separator 12 # 分隔符不能为空 13 14 >>> s1.partition(' ') 15 ("I'm", ' ', 'a super student.') 16 17 >>> s1.partition('abc') 18 ("I'm a super student.", '', '')
-
- rpartition(sep) -> (head,sep,tail)
- 从右到左,从左到右,遇到分隔符就把字符串分割成两部分,返回头、分隔符、尾三部分的三元组;如果没有找到分隔符,就返回2个空元素和尾的三元组
- rpartition(sep) -> (head,sep,tail)
字符串的大小写
- upper() -> 全大写
- lower() -> 全小写
- 大小写,做判断的时候用
- swapcase() -> 交互大小写
1 >>> s1 = "I'm a super student." 2 >>> s1.upper() 3 "I'M A SUPER STUDENT." 4 5 >>> s1.lower() 6 "i'm a super student." 7 8 >>> s1.swapcase() 9 "i'M A SUPER STUDENT."
字符串排版
- title() -> str
- 标题的每个单词都大写
- capitalize() -> str
- 首个单词大写
- center(width[,fillchar]) -> str
- width 打印宽度
- fillchar 填充的字符
- zfill(width) -> str
- width 打印宽度,居右,左边用0填充
- ljust(width[,fillchar]) -> str 左对齐
- rjust(width[,fillchar]) -> str 右对齐
1 >>> s = "I'm a super STUDENT." 2 >>> s.title() 3 "I'M A Super Student." 4 5 >>> s.capitalize() 6 "I'm a super student." 7 8 >>> s.center(20) 9 "I'm a super STUDENT." 10 11 >>> s.center(50) 12 " I'm a super STUDENT. " 13 14 >>> s.center(50,'#') 15 "###############I'm a super STUDENT.###############" 16 17 >>> s.zfill(50) 18 "000000000000000000000000000000I'm a super STUDENT." 19 20 >>> s.ljust(50,'#') 21 "I'm a super STUDENT.##############################" 22 23 >>> s.rjust(50,'#') 24 "##############################I'm a super STUDENT."
字符串修改
- replace(old,new[,count]) -> str
- 字符串中找到匹配替换为新子串,返回新字符串
- count表示替换几次,不指定就是全部替换
1 >>> 'www..magedu.com'.replace('w','p') 2 'ppp..magedu.com' 3 4 >>> 'www..magedu.com'.replace('w','p',2) 5 'ppw..magedu.com' 6 7 >>> 'www..magedu.com'.replace('w','p',1) 8 'pww..magedu.com' 9 10 >>> 'www..magedu.com'.replace('ww','p',2) 11 'pw..magedu.com' 12 13 >>> 'www..magedu.com'.replace('www','python',2) 14 'python..magedu.com'
- string([chars]) -> str
- 从字符串两端去除指定的字符集chars中的所有字符
- 如果chars没有指定,去除两端的空白字符
- lstrip([chars]) -> str 从左开始
- rstrip([chars]) -> str 从右开始
1 >>> s = "\r \n \t Hello Python \n \t" 2 >>> s.strip() 3 'Hello Python' 4 # 默认去掉两端的空白字符 5 6 >>> s1 = " I am very very very sorry " 7 >>> s1.strip() 8 'I am very very very sorry' 9 10 >>> s1.strip('r') 11 ' I am very very very sorry ' 12 # 因为首尾两端都没有r,因此无修改 13 14 >>> s1.strip('r y') 15 'I am very very very so' 16 # 这里要注意,去除的是r、空格和y这三个字符,首端查找有空格去掉,尾端先去掉空格,再去掉字符y,再去掉两个字符r 17 18 >>> s1.strip('r yIamso') 19 'very very ve' 20 21 >>> s1.lstrip('r yIamso') 22 'very very very sorry ' 23 24 >>> s1.rstrip('r yIamso') 25 ' I am very very ve' 26 >>>