1 # 1. find 查找目标单词,并返回下标
2 word = "i am zhangsan woxiang xue python wo yao haohao xuexi "
3 print(word.find("wo")) # 从 0 数起 应该是第 14 个字符(包含空格,空格占一个字符)
4 print(word.find("wo123")) # 如果要找的字符串不存在,返回 -1
5 """
6 其含义是说从下表为 15 位开始往后查找 "wo"这个关键词
7 因为后面还有一个 所以也能正常返回
8 """
9 print(word.find("wo",15,len(word)))
10
11 # 2. index 判断目标单词出现的下标
12 # 跟 find() 方法一样,不过如果要找的字符串不再 word 中会报错~
13 word = "i am zhangsan woxiang xue python wo yao haohao xuexi "
14 print(word.index("wo")) # 14
15 print(word.index("yao")) # 36
16 # print(word.index("abc")) # 报错 ValueError: substring not found
17
18 # 3. count 统计、计数
19 # 使用方法同 find() 方法
20 word = "i am zhangsan woxiang xue python wo yao haohao xuexi "
21 print(word.count("y")) # "y" 在字符串中出现两次,故返回 2
22 print(word.index("o",6,len(word))) # 15
23 print(len(word)) # 53
24
25 # 4. replace 替换单词
26 word = "i am zhangsan woxiang xue python wo yao"
27 """
28 加数字的意思就是代表替换几次
29 """
30 print(word.replace("wo","WO")) # i am zhangsan WOxiang xue python WO yao
31 print(word.replace("wo","WO",1)) # i am zhangsan WOxiang xue python wo yao
32
33 # 5. split 切片
34 """
35 格式:
36 split("切割符",[次数]) # []为可选参数
37 返回一个列表
38 """
39 word = "i am zhangsan woxiang xue python wo yao"
40 print(word.split(" ")) # ['i', 'am', 'zhangsan', 'woxiang', 'xue', 'python', 'wo', 'yao']
41 print(word.split(" ",2)) # ['i', 'am', 'zhangsan woxiang xue python wo yao']
42
43 # 6. strip 删除字符串两端的空白字符
44 """
45 格式:
46 word.strip([chars])
47 chars -- 移除字符串头尾指定的字符序列
48 """
49 word = "xxxx i am zhangsan woxiang xue python wo yao xxxx"
50 print(word.strip("xxxx")) # i am zhangsan woxiang xue python wo yao
51 word = " i am zhangsan woxiang xue python wo yao "
52 print(word.strip(" ")) # i am zhangsan woxiang xue python wo yao
# 思考
"""
给定一个字符串,a = "abcdefg hijklmn opqrst uvwxyz" 返回使用 或者空格分隔的倒数第二个字符串
"""
a = "abcdefg hijklmn opqrst uvwxyz"
b = a.split()
print(b) # ['abcdefg', 'hijklmn', 'opqrst', 'uvwxyz']
print(len(b)) # 4
print(b[len(b)-2]) # opqrst
点击查看答案