# 7. 字符串格式化输出# format 玩法1:等价于占位符
res = 'my name is {} my age is {}'.format('jason', 123)
print(res) # my name is jason my age is 123# format 玩法2:索引取值并支持反复使用
res = 'my name is {0} my age is {1} {0}'.format('jason', 123)
print(res) # my name is jason my age is 123 jason# format 玩法3:占位符见名知意
res = 'my name is {name1} my age is {age1} {name1}'.format(name1 = 'jason', age1 = 123)
print(res) # my name is jason my age is 123 jason# format 玩法4:推荐使用(*****)
name = input('username>>>:') # jason
age = input('age>>>:') # 18
res = f'my name is {name} my age is {age}'print(res) # my name is jason my age is 18
字符串需要了解的方法
# 1. 大小写相关
res = 'hElLO WorlD 666'print(res.upper()) # HELLO WORLD 666print(res.lower()) # hello world 666"""
图片验证码:生成没有大小统一的验证码展示给用户看
获取用户输入的验证码 将用户输入的验证码和当初产生的验证码统一转大写或者小写再比对
"""
code = '8ja6Cc'print('展示给用户看的图片验证码', code)
confirm_code = input('请输入验证码').strip()
if confirm_code.upper() == code.upper():
print('验证码正确')
res = 'hello world'print(res.isupper()) # Falseprint(res.islower()) # True
# 2. 判断字符串中是否是纯数字
res = ''print(res.isdigit())
guess_age = input('guess_age>>>:').strip()
if guess_age.isdigit():
guess_age = int(guess_age)
else:
print('年龄都不知道怎么输吗???')
# 3. 替换字符串中指定的内容
res = 'my name is jason jason jason jason'print(res.replace('jason','tony')) # my name is tony tony tony tonyprint(res.replace('jason', 'tony', 1)) # my name is tony jason jason jason 从左往右替换指定个数内容
# 7. 其它方法补充
res = 'helLO wORld hELlo worLD'print(res.title()) # Hello World Hello World 每个单词首字母大写print(res.capitalize()) # Hello world hello world 第一个单词首字母大写print(res.swapcase()) # HELlo WorLD HelLO WORld 原字符串单词取相反结果print(res.index('O')) # 4print(res.find('O')) # 4# print(res.index('c')) # 找不到直接报错print(res.find('c')) # -1 找不到默认返回-1print(res.find('LO')) # 3
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗