Python 字符串的索引、切片、拼接、获取长度、是否包含操作
字符串属于序列类型,所谓序列指的是一块可存放多个值得连续内存空间,这些值按一定的顺序排列,可通过每个值所在位置的编号(称为索引)访问它们。
1.字符串索引操作:字符串[索引],取出字符串中指定索引位置的字符
message = "hello word"
print(message[0])
print(message[-1])
print(message[9])
2.字符串切片操作: 字符串[开始索引:结束索引:步长],顾头不顾尾
- 开始索引若缺省,则默认从0开始
- 结束索引若缺省,则默认取出从开始索引后的所有内容
- 步长默认为1,可不指定,
- 步长为1时指从左往右按着取出
- 步长为2时指从左往右跳过一个取出一个
- 步长为-1时指从右往左按着取出
message = "hello word"
print(message[0:5])
print(message[:5])
print(message[-10:-5])
print(message[0:5:2])
print(message[:])
print(message[0:10])
print(message[0:])
print(message[-10:])
print(message[::-1])
3.字符串的拼接
name = "张同学"
age = 18
s1 = "我是:" + name + ",我的年龄是:" + str(age) + "岁!"
print(s1)
s2 = f"我是:{name},我的年龄是:{str(age)}岁!"
print(s2)
print("*" * 10)
4.计算字符串的长度:内置函数:len()
message = "hello word"
print(len(message))
5.字符串的判断是否包含:(x1 in x2)判断x1字符串是否在字符串x2中存在
message = "hello word"
print("hello" in message)
print("o w" in message)
print("words" in message)
print("hlo" in message)