字符串是Python的一个基本数据类型,python为字符串对象提供了很多方法才操作他们。
首先,一条print语句,介绍一下字符串方法都有哪些?
print(dir(str))
[...,'capitalize', 'casefold', 'center', 'count', 'encode',
'endswith','expandtabs', 'find', 'format', 'format_map',
'index', 'isalnum','isalpha', 'isascii', 'isdecimal',
'isdigit', 'isidentifier','islower', 'isnumeric','isprintable',
'isspace','istitle','isupper','join','ljust', 'lower', 'lstrip',
'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust',
'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith',
'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
其中主要分为十大类,
1. 大小写转换
2. 字符串填充
3. 字符串编码
4. 字符串格式化
5. 判断问题
6. 字符串查找
7. 字符串修剪
8. 拼接为字符串
9. 字符串替换
10. 字符串加密解密
自然语言处理领域常用的主要是5-9大类方法。下文将对这几类的方法进行简单介绍。
判断问题
凡是和判断有关的函数,直接敲一个is ,基本上都能查看到具体有哪些方法,这里不多做解释。
'isalnum','isalpha',
'isascii', 'isdecimal',
'isdigit', 'isidentifier',
'islower', 'isnumeric',
'isprintable', 'isspace',
'istitle','isupper'
字符串查找
关于字符串查找,主要方法有以下四个。他们各自的用法是:
'rfind', 'rindex','find','index'
str.find()
描述:查找字符串中指定的子字符串sub第一次出现的位置,可以规定字符串的索引查找范围。若无则返回 -1。
语法:str.find(sub,start,end)
-> int 返回整数
- sub ——要索引的子字符串。
- start ——索引的起始位置。默认值为0
- end ——索引的结束位置。默认值为字符串长度len(str)。[start,end) 不包括end。
例子:
s="I love python"
#查找子字符串"o"
s.find('o')
3
#索引起始位置为4 索引范围为:ve python
s.find('o',4)
11
#索引起始位置为4,结束位置为12 索引范围为:ve pytho
s.find('o',4,12)
11
s.find('o',4,11)#不包括11位的'o',返回-1
拼接为字符串
join() 函数(重点)
描述:将iterable变量的每一个元素后增加一个str字符串。
iterable又称:可迭代对象,包括:
字符串string
列表list
元组tuple
字典dict
集合set
生成器generator
等
语法: sep.join(iterable)
- sep——分隔符。可以为空。
- iterable—— 要连接的变量 ,可以是 字符串,元组,字典,列表等
例子:
s='好好学习,天天向上'
t=('1','2','3')
dic={'name':"Jack",'gender':'male','from':'China','age':18}
" ".join(s),"".join(t),"_".join(dic)
('好 好 学 习 , 天 天 向 上', '123', 'name_gender_from_age')
字符串替换
包括了:expandtabs()和replace()函数,经常使用到的是replace函数。
replace()函数
描述:把str.中的 old子串 替换成 new子串,如果 count 指定,则替换不超过 count次.。
语法:str.replace(old, new, count)
- old —— 将被替换的子字符串。
- new —— 新子字符串,用于替换old子字符串。
- count —— 替换的次数,默认全部替换。
例子:
s="我喜欢用Java编程,Java是世界上最强的编程语言!"
s,s.replace("Java",'Python',1),s.replace("Java",'Python')
('我喜欢用Java编程,Java是世界上最强的编程语言!',
'我喜欢用Python编程,Java是世界上最强的编程语言!',
'我喜欢用Python编程,Python是世界上最强的编程语言!')