2022.07.05 DAY5
1. 字符串基础
1. str()实现数字转型字符串
-
str()可以帮助我们将其他数据类型转换成字符串。
# str() 数字转字符串 def test(): a = 520 print(f"a = {a}") aToString = str(a) print(f"aToString = {aToString}") # Main if __name__ == '__main__': test()
2. 使用[]提取字符
- 在字符串后面添加[] ,[]里边是指定的偏移量,可以提取带位置的单个字符。
- 正向搜索
- 字符从0至len(str)-1进行编号。
- 反向搜索
-
尾部到头从-1到-len(str)进行编号。
# []提取字符 def test2(): myWords = "I Love You." print(myWords) print(f"myWords[0] = {myWords[0]}") print(f"myWords[len(myWords) - 1] = {myWords[len(myWords) - 1]}") print(f"myWords[-1] = {myWords[-1]}") print(f"myWords[-len(myWords)] = {myWords[-len(myWords)]}") # Main if __name__ == '__main__': test2()
-
3. replace()实现字符串替换
-
字符串是“不可改变”的。
-
需要替换某些字符。这时,只能通过创建新的字符串实现。
-
要改变原来的字符串,需要a = a.replace(…)
-
str.replace(old,new,max) # 将str中的old换成new,最多换max次
# replace()字符串替换 def test3(): myWords = "I Love You." print(f"myWords = {myWords}") newWords = myWords.replace("You", "Moon and stars") print(f"newWords = {newWords}") # Main if __name__ == '__main__': test3()
4. 字符串切片slice操作
-
切片slice操作可以让我们快速地提取子字符串。
-
标准格式为:[起始偏移量start : 终止偏移量end : 步长step]
-
典型操作(三个量为正数的情况)如下:
- [:] 提取整个字符串
- [start:] 从start索引开始到结尾
- [:end] 从头开始直到end-1
- [start:end] 从start到end-1
- [start: end:step] 从start提取到end-1,步长step
-
操作数为负数
-
[-3:] 倒数三个
-
[-8:-3] 倒数第八个到倒数第三个(包头不包尾)
-
[::-1] 步长为负,从右到左反向提取
# slice切片 字符串提取 def test4(): myWords = "I Love You." print(f"myWords[:] = {myWords[:]}") print(f"myWords[6:] = {myWords[2:]}") print(f"myWords[:6] = {myWords[:6]}") print(f"myWords[2:6] = {myWords[2:6]}") print(f"myWords[2:8:2] = {myWords[2:8:2]}") print(f"myWords[-3:] = {myWords[-3:]}") print(f"myWords[-8:-3] = {myWords[-8:-3]}") print(f"myWords[::-1] = {myWords[::-1]}") # Main if __name__ == '__main__': test4()
-
-
起始偏移量和终止偏移量不在[0,len(str)-1]内,也不会报错。
-
起始偏移量小于0则会当成0,终止偏移量大于len(str)-1会被当成-1。
5. split()分割和join()合并
-
split()可以基于指定分隔符将字符串分隔成多个子字符串(存储到列表中)。如果不指定分隔符,则默认使用空白字符(换行符/空格/制表符)。示例代码如下。
# split()分隔 def test5(): myWords = "I Love You." print(f"myWords.split() = {myWords.split()}") print(f"myWords.split('Love') = {myWords.split('Love')}") # Main if __name__ == '__main__': test5()
-
join()的作用和split()作用刚好相反,用于将一系列子字符串连接起来。
-
格式 : ‘’.join(a)
# join()合并 def test6(): myWords = ['I love you.', 'But,', 'love is broken.'] print(f"''.join(myWords) = {''.join(myWords)}") # Main if __name__ == '__main__': test6()
-
join()比+的性能更好。join只生成一个对象,而+会生成多个对象。
# 比较join 和 + 的效率 def cmp(): time1 = time.time() # 起始时刻 a = '' for i in range(1000000): a += 'I Love You.' time2 = time.time() # 终止时刻 print(f" + 运算时间 = {time2 - time1}") time1 = time.time() # 起始时刻 li = [] for i in range(1000000): li.append('I Love You.') a = "".join(li) time2 = time.time() # 终止时刻 print(f"join 运算时间 = {time2 - time1}") # Main if __name__ == '__main__': cmp()
6. 字符串驻留机制和字符串比较
- 字符串驻留
- 仅保存一份相同且不可变字符串的方法,不同的值被存放在字符串驻留池中。
- Python支持字符串驻留机制,对于符合标识符规则的字符串会启用字符串驻留机制。
- 仅包含下划线_、字母和数字。
- 如果 a = “a_b” , b = “a_b” , 则a is b 为True。
- is/not is 比较 id , ==/!= 比较 value。
7. 成员操作符
- in/not in 判断某个关键字(子字符串)是否存在于字符串中。