新的学习历程-python6 字符串基础使用

 1 sentence1 = 'tom\'s pet is a cat'  # 单引号中包含转单引号
 2 sentence2 = "tom\'s pet is a cat"
 3 sentence3 = "tom said:\"hello world\""
 4 sentence4 = 'tom said:"hello world"'
 5 words = '''
 6 hello
 7 world
 8 abc
 9 '''  # 连续三个单引号或双引号可以保存输入格式,允许输入多行字符串
10 print(words)
11 
12 py_str = "python"
13 len(py_str)  # 取长度
14 py_str[0]  # 取第一个字符
15 'python'[0]
16 py_str[-1]  # 最后一个字符
17 # py_str[8] #错误,下标超出范围
18 py_str[2:4]  # 切片 包含起始下标,不包含结束下标
19 py_str[:2]  # 从开头取到下标为2之前的字符
20 py_str[2:]  # 从下标为2的字符取到结尾
21 py_str[:]  # 取全部
22 py_str[::2]  # 步长为2,默认是1
23 py_str[1::2]  # 取出yhn
24 py_str[::-1]  # 步长为-1 表示自右向左取
25 
26 py_str + "is good"  # 简单拼接字符串
27 py_str * 3  # 把字符串重复3遍
28 
29 "t" in py_str  # True
30 "th" in py_str  # True
31 "to" in py_str  # False
32 "to" not in py_str  # True

学习资源来自:张志刚老师python百例 《例解Python:Python编程快速入门践行指南 张志刚 电子工业出版社》【摘要 书评 试读】- 京东图书 (jd.com)

posted @ 2022-11-14 23:15  usolo  阅读(38)  评论(0)    收藏  举报