1.字符串的简介
字符串通常是指你想要展示给别人的、或者是你想要从程序里“导出”的一小段字符。Python可以通过文本里的双引号 " 或者单引号 ’ 识别出字符串来。这在你以前的 print 练习中你已经见过很多次了。如果你把单引号或者双引号括起来的文本放到 print 后面,它们就会被python打印出来。
2.字符串的定义
a = 'hello' ##正常的字符串定义方式为加单引号或者双引号
b = 'what\'s up' ##如果字符串中出现单引号时可以用\来转义
c = "what's up" ##还可以直接使用双引号来避免单引号
print(a) #
print(b) #输出字符串a,b,c
print(c) #
上述代码的输出结果:
3.字符串的特性
1.索引
s = 'hello'
print(s[0])
print(s[1])
上述代码的输出结果:
2.切片
print(s[0:3]) # 切片的规则:s[start:end:step] 从start开始到end-1结束,步长:step
print(s[0:4:2])
上述代码的输出结果:
3.显示
print(s[:]) #显示所有字符
print(s[:3] ) #显示前3个字符
print(s[::-1]) #对字符串倒叙输出
print(s[1:]) #除了第一个字符以外,其他全部显示
上述代码的输出结果:
4.重复
print(s * 5) #把字符串s重复输出5遍
上述代码的输出结果:
5.连接
print(s + 'world') #在字符串s后追加输出world
上述代码的输出结果:
6.成员操作符
print('h' in s) #查看字符串s里面是否存在h
上述代码的输出结果:
7.for循环(迭代)
for i in s:
print(i)
上述代码的输出结果: