按索引取值

1
2
3
4
5
6
7
8
# 按索引取值
msg = 'hello world'
print(msg[1]) # 正向取
print(msg[5]) # 空也可以取
print(msg[-1]) # 反向取
# 只能取不可以改
res = msg[1] == 'H'
print(res) # False

切片

1
2
3
4
5
# 取头不取尾
msg = 'hello world'
res = msg[0:5]
print(res) # hello
print(msg) # hello world
1
2
3
4
5
# 取头不取尾
msg = 'hello world'
res = msg[0:5:2]
print(res) # hlo
print(msg) # hello world

.strip()相关知识

.strip()只可以去两边

1
2
3
4
5
6
7
8
9
10
11
12
13
14
msg = '     bage       '
res = msg.strip()
print(res) # bage

msg = '*****bage*****'
print(msg.strip('*')) # bage

# 只去两边,不去中间
msg = '****ba****ge****'
print(msg.strip('*')) # ba****ge


msg = '-=*&bage-=-' # bage
print(msg.strip('=-*&'))

.lstrip()只可以左去边

1
2
3
4
5
6
7
8
9
10
msg = '     bage       '
res = msg.lstrip() # bage
print(res)
# 只去左边
msg = '*****bage*****' # bage*****
print(msg.lstrip('*'))

# 只去左边
msg = '****ba****ge****' # ba****ge****
print(msg.lstrip('*'))

.rstrip()只可以右去边

1
2
3
4
5
6
7
8
9
10
11
# 只去右边
msg = ' bage '
res = msg.rstrip() # bage
print(res)
# 只去右边
msg = '*****bage*****' # *****bage
print(msg.rstrip('*'))

# 只去右边
msg = '****ba****ge****' #****ba****ge
print(msg.rstrip('*'))

.strip的应用
当用户输入空格时,不影响操作

1
2
3
4
5
6
uers = input('请输入姓名:').strip()
pwd = input('请输入密码:').strip()
if uers == 'bage' and pwd == '123':
print('登入成功')
else:
print('姓名或密码错误')

.split()相关知识

可以把字符串切分为列表

.split()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 默认根据空格切分
sp = 'my name is bage'
print(sp.split())

# 指定符号切分
sp = 'my:name:is:bage'
print(sp.split(':'))

# 指定切分次数
sp = 'my:name:is:bage'
print(sp.split(':', 1))

# 循环
sp = 'my:name:is:bage'
for x in sp:
print(x)

.rsplit()

1
2
3
# 指定切分次数,从右往左
sp = 'my:name:is:bage'
print(sp.rsplit(':', 1)) # ['my:name:is', 'bage']

lower与upper相关知识

1
2
3
name = 'bAGe'
print(name.lower()) # bage
print(name.upper()) # BAGE

.join相关知识

1
2
3
4
5
l = ["bage",'19','play']
ress = l[0] + ':' + l[1] + ':' + l[2] #傻子才用
res = ':'.join(l) #根据分隔符将列表合并为字符串(只限列表里面为字符串)
print(ress)
print(res)

.replace替换 相关知识

1
2
3
4
msg = 'my name is bage my name is bage'
print(msg.replace('my', 'MY')) # 替换
print(msg.replace('my', 'MY', 1)) # 指定替换

.isdigit相关知识

判断字符串是否全为数字组成

1
2
3
4
5
6
7
8
9
10
11
age = input('猜猜我我的年龄:').strip()
if age.isdigit():
age = int(age)
if age > 19:
print('太大了')
elif age < 19:
print('太小了')
elif age == 19:
print('太牛了,你猜对了')
else:
print('输数字,傻子')