1.字符串可以用单引号双引号三引号定义
''、""、''' '''
三引号:支持跨行的字符串
ptr='''大佬
请您教俺本领!!
!!
666
'''
print(ptr)
执行结果:
![](https://i-blog.csdnimg.cn/blog_migrate/62709de64e4d960b1c900f71a33b7d68.png)
如果是单引号,或者双引号换行就要用\n了(和C或JAVA类似)
如果字符串对象中有引号怎么办呢
换个不同的1就好啦,例如字符串中的内容是单引号,那么就剋用双引号或者三引号括起来整个字符串。
(要注意的是双引号是一个双引号,而不是两个单引号,而三引号是三个单引号)
如果既有单引号又有双引号,就要用三引号括起来了。
刚刚看到一个三引号的另一个用法是多行注释,浅浅的记下来吧:
"""
这是一个
多行注释
注释
"""
data = """name # 姓名
age # 年龄
sex # 性别
"""
print(data)
![](https://i-blog.csdnimg.cn/blog_migrate/3d8535bda0d70b0bdcdb58d3230f54fe.png)
2.字符串拼接:
和java类似
print('做'+"个试验")
![](https://i-blog.csdnimg.cn/blog_migrate/ee7fc6dabb5cc60cca24023771bbf503.png)
print('做'+"'''个试验'''")#里边可以含有三引号
![](https://i-blog.csdnimg.cn/blog_migrate/eb80870661ef6d555851ed2d54989b31.png)
print('再做'+'''个试验''')#单引号和三引号拼接
![](https://i-blog.csdnimg.cn/blog_migrate/5a261cc865c576d26bdc761922e2e32b.png)
3.字符串元素的索引
由一个个元素依次组成的字符串,python中把这种特性的数据称之为sequence
(序列)
'浅浅的做个实验'
其实和c中的数组类似,或者字符串数组。
以上几个字的索引依次是0123456
用法如下:
test='浅浅的做个实验'
print(test[0])
结果如下:
![](https://i-blog.csdnimg.cn/blog_migrate/a7da8fc9e458dc25d6d67bc68196c189.png)
需要注意的是不要越界,类似于数组越界
py中索引也可以是负数
我理解的是从右向左,从-1开始,依次到最后一个元素
test='浅浅的做个实验'
print(test[-1])
print(test[-7])
结果如下
![](https://i-blog.csdnimg.cn/blog_migrate/931920fe96666bc33d18e59f016814eb.png)
负数的作用大概就是当字符串特别长的时候,我们可以用-1表示最后一个省事一点
4.字符串切片(从中切出一部分类似于-子字符串提取)
sequence特性的数据对象都支持切片操作,字符串具有sequence特性的,所以也支持切片。
切法:(第一个字的下标到最后一个字的下标加一)
字符串名字[要提取的第一个字的下标:要提取的最后一个字的下标+1]
# 0 1 2 3 4 5 6
test='做一个切片实验'
# -7-6-5-4-3-2-1
print(test[0:3])
print(test[-7:-4])
![](https://i-blog.csdnimg.cn/blog_migrate/5de7355d58a40d88752b6e84d41f5687.png)
如果后边的下标省略,意思就是说一直提取到最后
# 0 1 2 3 4 5 6
test='做一个切片实验'
# -7-6-5-4-3-2-1
print(test[0:])
print(test[-7:])
![](https://i-blog.csdnimg.cn/blog_migrate/0d72a14474d2914b91860d24bbdb0b46.png)
前边也可以省略,意思是从第一个开始
还可以拼接下嘞
# 0 1 2 3 4 5 6
test='做一个切片实验'
# -7-6-5-4-3-2-1
print(test[:3]+test[3:])
print(test[:-4]+test[-4:])
![](https://i-blog.csdnimg.cn/blog_migrate/e261696c4b9a5ddb2926d8c576e36350.png)
如果都省略呢?
会全部输出,和直接print(字符串名效果一样)
# 0 1 2 3 4 5 6
test='做一个切片实验'
# -7-6-5-4-3-2-1
print(test[:])
print(test[:])
![](https://i-blog.csdnimg.cn/blog_migrate/94ad7b56d6e5eef440bb2e91dfe93589.png)
5.获取字符串函数:
内置函数len可以用来获取字符串的长度
test='一个长度实验'
print(len(test))
![](https://i-blog.csdnimg.cn/blog_migrate/f1772b671e801b571c3a8730c35a4121.png)