Python程序设计基础第七章笔记:字符串
Python程序设计基础笔记
目录
- Python程序设计基础笔记
- 第七章:文本处理(一):字符串
-
-
7.1 字符串编码格式简介
-
7.2 转义字符与原始字符串
-
7.3 字符串格式化
-
- 7.3.1 使用 % 进行格式化
- 7.3.2 使用 format() 方法进行字符串格式化
- 7.3.3 格式化的字符串常量
- 7.3.4 使用 Template 模板进行格式化
-
7.4 字符串常用操作
-
- find() rfind() index() rindex() count():在字符串中查找字符串
- split() rsplit() partition() rpartition():分离字符串
- join():整合字符串
- lower() upper() capitalize() title() swapcase():转变字符串
- replace() maketrans() translate():替代字符串
- strip() rstrip() lstrip():缩小字符串
- startswith() endswith():检查字符串
- isalnum() isalpha() isdigit() isdecimal() isnumeric() isspace() isupper() islower():检查字符串
- center() ljust() rjust() zfill():字符串排版
- 字符串对象支持的运算符
- 适用于字符串对象的内置函数
- 字符串对象的切片操作
-
7.5 字符串常量
-
7.6 中英文分词
-
7.7 汉字到拼音的转换
-
第七章:文本处理(一):字符串
字符串属于有序不可变序列,支持序列通用操作(双线索引,比较大小,计算长度,元素访问,切片,成员测试等),还支持一些其他如字符串格式化、查找、替换、排版等操作。不可以直接对字符串进行元素的修改。
将字符串转化为字节串:
'字符串'.encode() ==>b'\xe5\xad\x97\xe7\xac\xa6\xe4\xb8\xb2' #默认以 utf-8 形式编码
_.decode() ==>'字符串'
'字符串'.encode('gbk') ==>b'\xd7\xd6\xb7\xfb\xb4\xae'
7.1 字符串编码格式简介
ASCII:最早的编码格式,采用一个字节来对字符进行编码,最多表示256个符号。
UTF-8:全面支持中文,一个字节表示英文,三个字节表示中文,兼容 ASCII 。是 python 的默认编码格式,无论是数字、英文还是中文,都按一个字符处理(区别于 字节 )。
GB2312 GBK CP936:和中文有关的编码格式,两个字节表示中文。
import sys
sys.getdefaultcoding() ==>'utf-8' #查看默认编码格式
7.2 转义字符与原始字符串
转义字符键 P152 表7-1。
在字符串之前加上 r 或者 R 代表原始字符串,不进行任何转义,适合在文件路径,URL和正则表达式中的表达。
7.3 字符串格式化
7.3.1 使用 % 进行格式化
语法格式如下:
‘% [-] [+] [0] [m] [.n] 格式字符’ % x
分别表示:开始、指定左对齐输出、对正数加正号、指定空位填 0 、指定最小宽度、指定精度、指定类型、格式运算符、待转换的表达式
7.3.2 使用 format() 方法进行字符串格式化
Python 社区更推荐使用此种方法进行格式化。
format() 是字符串类的公有方法,参数可以是一个,也可以是多个,也可以是一个序列,多个序列。字符串中带转换的表达式可以像关键参数一样,在字符串中的 { } 内写出来,并在format() 的参数列表中显式赋值,也可以以 {数字 :格式化格式} 的形式格式化。
f = 'The number {0:,} in hex is: {0:#_x} , in oct is {0:#_o} , \ {1:,} in hex is:'
+' {1:#_x}'.format #在 {0:,} 中,0 表示参数列表的第一位, : 表示后面是要格式化的形式 ,, 表示用 , 分割长数字, {0:#_x} 中的 # 表示输出进制前缀
f(123456789,2000000000) ==>'The number 123,456,789 in hex is: 0x75b_cd15 , in oct is 0o7_2674_6425 , 2,000,000,000 in hex is: 0x7735_9400'
lst = [123456789,2000000000]
f = 'The number {0[0]:,} in hex is: {0[0]:#_x} , in oct is {0[0]:#_o} , {0[1]:,} in hex is: {1:#_x}'.format
#format 是字符串这个类的内置方法,在 f 中,字符串的实例是 'The number {0[0]:,} in hex is: {0[0]:#_x} , in oct is {0[0]:#_o} , {0[1]:,} in hex is: {1:#_x}'
f(lst) ==>'The number 123,456,789 in hex is: 0x75b_cd15 , in oct is 0o7_2674_6425 , 2,000,000,000 in hex is: 0x7735_9400'
#f 的参数是 lst
'my name is {name}, my age is {age}'.format(age = 23, name = lihua)
==>'my name is lihua, my age is 23' #支持关键参数
7.3.3 格式化的字符串常量
字符串前加 f 。
width, precision, value = 10, 4, 11/3
f'result:{value : {width}.{precision}}' ==>'result: 3.667' #width 是最小宽度,3.667是五个字节,所以要留出 5 个空格,precision 指精度 ,必须要在花括号内再套一个花括号来格式后面的两个值
7.3.4 使用 Template 模板进行格式化
from string import Template
t = Template('My name is ${name} and my age is ${age}')
d = {name:'zhangsan' , age:18}
t.substitute(d)
==>'My name is zhangsan and my age is 18'
7.4 字符串常用操作
由于字符串不是不可变序列,所以对字符串的修改返回的字符串都是新字符串,并没有对源字符串作出修改。
find() rfind() index() rindex() count():在字符串中查找字符串
分别表示,第一次出现位置,最后一次出现位置,第一次出现位置,最后一次出现位置,出现次数
s = 'i am tired of notes'
s.find('tired',5,15)
Out[74]: 5
s.find('am',5,10)
Out[75]: -1
s.index('e')
Out[76]: 8
s.rindex('e')
Out[77]: 17
s.rindex('happy')
ValueError: substring not found
s.count('e')
Out[79]: 2
split() rsplit() partition() rpartition():分离字符串
split() rsplit()指定字符从左边、右边作为分隔符来分割字符串,默认值为空白字符,包括空格、换行符、制表符等,如果无参数,则将所有的,即使连续出现的空白符当作一个空白字符并用来分隔,如果给定分隔符,则将每一个分隔符当独立的服啊后分割。默认值关键参数 maxsplit 默认值为无穷大,表示最大分割次数。返回列表,元素是被分割后的字符串部分。
partition() rpartition()只会分割一次,需要参数,返回列表,列表中只有三个元素为 分割前的字符串部分,分隔符号,分割后的字符串部分,若在字符串中找不到分隔符,返回空字符串与一个原字符串。
'i am so so\n\n\ntired of notes'.split()
Out[80]: ['i', 'am', 'so', 'so', 'tired', 'of', 'notes']
'i am so so\n\n\ntired of notes'.split('\n')
Out[81]: ['i am so so', '', '', 'tired of notes']
'i am so so tired of notes'.rpartition('so')
Out[82]: ('i am so ', 'so', ' tired of notes')
'i am so so\n\n\ntired of notes'.split(maxsplit = 5)
Out[83]: ['i', 'am', 'so', 'so', 'tired', 'of notes']
join():整合字符串
参数为一个元素全是字符串的序列,返回字符串。
可以用 join() 和 split() 来连接字符。
x = 'aaa bb c d e fff '
' '.join(x.split())
Out[2]: 'aaa bb c d e fff'
lower() upper() capitalize() title() swapcase():转变字符串
分来用来将字符串转化为小写、大写字符串,将字符串首字母变为大写,将每个单词的首字母变为大写,大小写互换。均生成新字符串而不对原字符串做修改。
x.lower()
Out[5]: 'katty is a cat'
x.upper()
Out[6]: 'KATTY IS A CAT'
x.capitalize()
Out[7]: 'Katty is a cat'
x.title()
Out[8]: 'Katty Is A Cat'
x.swapcase()
Out[9]: 'KATTY IS A cat'
replace() maketrans() translate():替代字符串
都是用来替换字符串中的内容,replace() 返回新字符串,maketraans() translate() 两个方法一般一起用。
'One of the classmates of John is the cousin of John'.replace('of','in')
Out[16]: 'One in the classmates in John is the cousin in John'
table = ''.maketrans('abcdefg','ABCDEFG')
'there are many uppercases'.translate(table)
Out[18]: 'thErE ArE mAny uppErCAsEs'
strip() rstrip() lstrip():缩小字符串
分别用来删除两端,右端和左端连续的空白字符或指定字符。返回新字符串。
'aabbccddeeeffg'.strip('gbaef')
==> 'ccdd'
#第一轮循环:aabbccddeeeff~~g~~ ,~~aa~~ bbccddeeeff,bbccddeee~~ff~~ ==>bbccddeee
#第二轮循环:~~bb~~ ccddeee,ccdd~~eee~~ ==>ccdd
#第三轮循环:ccdd ==>ccdd
#二三轮结果相同,不再循环
startswith() endswith():检查字符串
返回 True 或者 False,参数可以有1 、2 、3 个,分别表示开始(结束)字符、起始位置、结束位置。
'It is boring'.startswith('I',0,0)
Out[27]: False
'It is boring'.startswith('I',0,1)
Out[28]: True
'It is boring'.endswith('is',0,4)
Out[32]: False
'It is boring'.endswith('is',0,5) #注意起始和结束位置
Out[33]: True
isalnum() isalpha() isdigit() isdecimal() isnumeric() isspace() isupper() islower():检查字符串
分别用来检查 是否为数字或字母、字母、数字字符、数字字符、数字字符、空白字符、大写字母、小写字母,其中 isnumeric() 还支持汉字数字、罗马数字。
其中除了 isspace() 只判定纯空白字符(空格、换行、换页等)为 True,其他所有方法所判定为 True 的字符串对象中,都不能包括空白字符和运算符号字符,即使是小数点。
'\n\t'.isspace()
Out[12]: True
'123.4'.isalnum()
Out[1]: False
'123.4'.isdigit()
Out[2]: False```
center() ljust() rjust() zfill():字符串排版
这几个方法用来对字符串进行排版,返回新字符串。
center() ljust() rjust() 都有两个参数,第一个参数表示输出字符串的宽度,第二个参数表示填充物,为长度为一的字符串,默认是空格。zfill() 是右对齐,只有一个参数,表示返回字符串的宽度,填充物是 ‘0’ 。以上方法,当第一个参数小于原字符串长度的时候,返回新字符串与原字符串相同。
'center'.center(20,'=')
Out[15]: '=======center======='
'left'.ljust(15,'r')
Out[17]: 'leftrrrrrrrrrrr'
'right'.rjust(15,'l')
Out[19]: 'llllllllllright'
'center'.zfill(20)
Out[20]: '00000000000000center'
字符串对象支持的运算符
支持 + in * 等,但 + 的效率比较低,并且可能会产生大量的垃圾数据,建议使用 join()。
适用于字符串对象的内置函数
很多内置函数像 len() max() min() zip() sorted() reversed() enumerate() eval() 等支持对字符串进行操作。eval() 参数必须是字符串,用来计算字符串中的值。
import math
eval(math.sqrt(3))
TypeError: eval() arg 1 must be a string, bytes or code object
eval('math.sqrt(3)')
Out[32]: 1.7320508075688772
a ,b = 3 ,4
eval('a + 1')
Out[35]: 4
x = input()
ab
eval(x)
NameError: name 'ab' is not defined
ab = 1
eval(x)
Out[39]: 1
lst = input()
['a','b',15]
lst1 = list(lst)
lst1
Out[47]: ['[', "'", 'a', "'", ',', "'", 'b', "'", ',', '1', '5', ']']
eval(lst)
Out[48]: ['a', 'b', 15] #使用 eval() 将值为列表的字符串转化为列表
字符串对象的切片操作
切片也支持字符串,但只能取值,不支持修改。
7.5 字符串常量
import string
string.digits+ string.ascii_letters+ string.punctuation
Out[88]: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\ ]^_`{|}~'
7.6 中英文分词
主要介绍 jieba 模块 和 snownlp 模块
import jieba
import snownlp
x = '分词的准确度直接影响了后续文本处理和挖掘算法的最终效果'
jieba.cut(x)
print(list(_))
['分词', '的', '准确度', '直接', '影响', '了', '后续', '文本处理', '和', '挖掘', '算法', '的', '最终', '效果']
print(snownlp.snowNLP(x).words)
['分词', '的', '准确度', '直接', '影响', '了', '后续', '文本处理', '和', '挖掘', '算法', '的', '最终', '效果']
jieba.add_word('本来是要被分开的一句话') #为词库增加单词
list(jieba.cut('本来是要被分开的一句话'))
Out[65]: ['本来是要被分开的一句话']
7.7 汉字到拼音的转换
主要介绍扩展库 pypinyin
import pypinyin
from pypinyin import lazy_pinyin,pinyin
lazy_pinyin('逃离')
Out[69]: ['tao', 'li'] #返回拼音
lazy_pinyin('逃离',1) #带声调
Out[70]: ['táo', 'lí']
lazy_pinyin('逃离',2)
Out[71]: ['ta2o', 'li2']
lazy_pinyin('逃离',3)
Out[72]: ['t', 'l']
pinyin('重要')
Out[76]: [['zhòng'], ['yào']]
pinyin('重阳')
Out[77]: [['chóng'], ['yáng']] #识别多音字
pinyin('重阳节',heteronym = True)
Out[79]: [['chóng'], ['yáng'], ['jié', 'jiē']] #识别多音字并返回全部音,可能未更新扩展库导致出错
lazy_pinyin('中Englishi混合123',1) #区别中英文
Out[81]: ['zhōng', 'Englishi', 'hùn', 'hé', '123']
