Python基础(20) - 字符串支持的基本操作
2020-02-28 本文已影响0人
xianling_he
字符串常用操作 - 索引
- 使用[x]进行索引
s1 = 'hello world'
print(s1[0])
print(s1[1])

字符串常用操作 - 分片
- 使用[start:end]进行分片操作
- end是闭合选项,就是end-1才是有效是输出
s1 = 'hello world'
print(s1[6:9])

- 如果end不跟参数就是从起始start一直到结束
s1 = 'hello world'
print(s1[6:])

- 使用[:::2] 其中2表示步长是多少,2表示每隔一个进行取值
s1 = 'hello world'
print(s1[::2])

- 使用[::1] 其中1表示取所有的字符串
s1 = 'hello world'
print(s1[::1])

- 使用[::-1] 其中-1表示取所有的字符串,然后反向输出
s1 = 'hello world'
print(s1[::-1])

字符串常用操作 - 乘法
- 使用乘号(*) 进行重复输出
s1 = 'hello world '
print(s1 * 10)

字符串常用操作 - 运算符in, not in的使用
- 判断字符串是否在其中,使用in
- 判断字符串是否不在其中,使用not in
s1 = 'abcdefg'
print('a' in s1)
print('x' not in s1)

字符串常用操作 - 获得字符串的长度len
s1 = 'abcdefg'
print(len(s1))

字符串常用操作 - 获得字符串的大小min,max
s1 = 'abcdefg'
print(min(s1))
print(max(s1))

总结
- 以上常用的字符串方法也能够适用于列表
- 字符串跟元组的特点是不能修改其值,但是列表可以单独赋值
- 列表赋值方法如S[0] = 10
加油 2020-2-28