一、作用
记录描述性质的状态
二、定义
s1 = 'hello' # s1 = str('hello')
print(type(s1)) # <class 'str'>
三、类型转换
str可以把任意类型转换为字符串类型
dic1 = {'a': 1}
s1 = str(dic1)
print(s1, type(s1)) # {'a': 1} <class 'str'>
四、使用:内置方法
4.1 优先掌握的操作
4.1.1 按索引取值
支持正向取和反向取,但是只能取、不能改,修改时会报错。
s1 = 'hello'
print(s1[0]) # h
print(s1[-1]) # o
s1[0] = 'H' # TypeError: 'str' object does not support item assignment
4.1.2 切片
顾头不顾尾、可指定步长。
s2 = 'hello world'
msg1 = s2[0:7] # hello w
# 步长
msg2 = s2[0:7:2]
print(msg1, msg2) # hlow
# 反向步长
msg3 = s2[::-1] # dlrow olleh
msg4 = s2[-1:0:-1] # dlrow olle
4.1.3 长度len
返回字符串长度。
s2 = 'hello world'
print(len(s2)) # 11
4.1.4 成员运算 in和not in
判断一个子字符串是否存在于大字符串中。
bool1 = 'he' in 'hello'
print(bool1) # True
bool2 = 'he' not in 'hello'
print(bool2) # False
4.1.5 移除空白 strip
默认去空格,只去两边不去中间,可指定多个字符。
s = ' hello world '
print(s.strip()) # hello world
s1 = '=/*/=hello=*/**//=='
print(s1.strip('=/*')) # hello
strip应用案例:
name = 'czp'
password = '970203'
for x in range(3):
inp_name = input('请输入用户名:').strip()
inp_password = input('请输入密码').strip()
if inp_name == name and inp_password == password:
print('登录成功')
break
else:
print('输错次数过多')
4.1.6 切分 split
把一个字符串按照某种分隔符进行切分,得到的结果是列表。默认的分隔符是空格,可以指定分隔符和分割次数。
info = 'czp 25 male'
res = info.split()
print(res) # ['czp', '25', 'male']
# 指定分隔符
info = 'czp:25 male'
res = info.split(':') # ['czp', '25 male']
print(res)
# 指定分割次数
info = 'czp 25 male'
res = info.split(' ', 1)
print(res) # ['czp', '25 male']
4.1.7 循环
for x in 'hello world':
print(x)
4.2 需要掌握的操作
4.2.1 strip、lstrip、rstrip
strip为两侧移除,rstrip为右侧移除,lstrip为左侧移除。
s = ' Hello world '
print(s.strip()) # 'Hello world'
print(s.rstrip()) # ' Hello world'
print(s.lstrip()) # 'Hello world '
4.2.2 lower、upper
lower:将字符串都转成小写。
upper:将字符串都转成大写。
s = 'Hello world'
print(s.lower()) # hello world
print(s.upper()) # HELLO WORLD
4.2.3 startswith、endswith
startswith:判断字符串是否以指定字符串开头。
endswith:判断字符串是否以指定字符串结尾。
s = ' Hello world '
print(s.startswith('He')) # False
print(s.endswith(' ')) # True
4.2.4 format的三种用法
4.2.5 split、rsplit
info = 'czp:25:male'
res1 = info.split(':') # ['czp', '25 male']
res2 = info.rsplit(':') # ['czp', '25 male']
print(res1, res2)
4.2.6 join
按某个分隔符将元素全为字符串的列表的每个元素拼接成一个大字符串。
msg = ['hello', 'world', '2021']
res = " ".join(msg)
print(res) # hello world 2021
4.2.7 replace
将某个子字符串替换为指定字符串,可指定替换次数。
msg = 'one world one dream'
msg1 = msg.replace('one', 'ONE') # ONE world ONE dream
msg2 = msg.replace('one', 'ONE', 1) # ONE world one dream
print(msg1, msg2)
4.2.8 isdigit
判断字符串是否全由数字组成
应用案例:
str_age = input('请输入你的年龄:') # 用户输入非数字时提醒用户而不是程序报错
if str_age.isdigit():
age = int(str_age)
if age >= 18:
print('成年')
else:
print('未成年')
else:
print('输入的年龄需为整数')