字符串定义
字符串定义:
\n:换行
\: 续行
\t: 空格
\ch:转义
s = ('hello'
'world') # 代码换行
print(s)
# \续行符
s = ('hello\
world') # 代码换行
print(s)
s = """
hello
world
"""
print(s) # 结果换行
print(r'D:\test\abc.txt')
print('D:\\test\\abc.txt')
# a=b=c=d=1
# if a==1 and b==2 and \
# c==3 and d==4:
print('"hello"')
print("'hello'")
print('''"hello"''')
print("\"")
字符串格式化
format(*args,**kwargs)
*args: 接受多个隔开的序列值 1,2,3
**kwargs:接受多个逗号隔开的关键字值
name = '张三'
age = 20
print(f'我的名字是{name},年龄是{age}')
"""
format(*args,**kwargs)
*args: 接受多个隔开的序列值 1,2,3
**kwargs:接受多个逗号隔开的关键字值
"""
print('我的名字是{},年龄是{}'.format(name, age))
# 序列对应后边的序列索引
print('我的名字是{0},年龄是{1}'.format(name, age))
print('我的名字是{a},年龄是{b}'.format(b=age, a=name))
# 今天是 2024年02月02日,星期一,今天的天气晴,气温15.4度
year = 2024
month = 2
day = 2
week = '一'
weather = '晴'
temperature = 15.4
print(f'今天是{year}年{month}月{day}日,星期{week},今天的天气{weather},气温{temperature}度')
字符串遍历
len()获取字符串长度
s = 'Hello World'
# 获取字符串长度,索引最大是长度-1
print(len(s))
# 根据索引获取对应字符
print(s[1], s[6])
# 遍历字符串
for index in range(len(s)):
# if s[index] == '1':
# print(index)
print(s[index], end=',')
print()
for ch in s:
print(ch, end=',')
print()
s = 'Hello World'
for index, ch in enumerate(s):
print(index, ch)
字符串常用方法
count: 统计某个字串出现的次数
# count: 统计某个字串出现的次数
# print(s.count('l')) # 3
# print(s.count('l', 7, 10)) # 1
# print(s.count('ll')) # 1
index根据子串查找第一个索引
print(s.index('l')) # 2 返回子串的第一个起始下标
print(s.rindex('l')) # 9, 从右向左检索
print(s.index('el')) # 1 返回子串的第一个起始下标
print(s.index('l', 7, 10)) # 9
print(s.index('qq')) # 抛出异常
split将一个字符串拆分为列表
print(s.split(' ')) # ['Hello', 'World']
print('a-b-c-d'.split('-', 2)) # ['a', 'b', 'c-d']
去掉前后缀 removeprefix removesuffix
# 去掉前后缀
print('<<hello>>'.removeprefix('<<')) # hello>>
print('<<hello>>'.removesuffix('>>')) # <<hello
# 链式写法
print('<<hello>>'.removeprefix('<<').removesuffix('>>')) # hello
替换replace
print('ab123412'.replace('12', 'cd')) # abcd34cd
print('ab123412'.replace('12', 'cd', 1)) # abcd3412
print('he<<llo>>'.replace('<<', '').replace('>>', '')) # hello
转换为大小写
print(s.upper())
print(s.lower())
字符串其他方法
s = 'hello world'
# 拆分
print(s.split(' ')) # ['hello', 'world']
# 连接
print('-'.join(['hello', 'world']))
# 左对齐,不足n位,右边填充指定字符
print('45'.ljust(5, '#')) # 45###
# 左对齐,不足n位,左边填充指定字符
print('45'.rjust(5, '#')) # ###45
# 两端对齐,不足n位,两边填充指定字符
print('hello'.center(10, '-'))
# 0填充
print('5'.zfill(2)) # 05
# 大驼峰
print('hello world'.title()) # 大驼峰
print('Hello World'.istitle()) # 是否大驼峰
字符串切片
s[start:end:step]
start:开始位置,开头或结尾默认不写,可正可负
end: 结束位置,,开头或结尾默认不写,可正可负
step: 跨越的步长,可正可负,1可以默认不写
如果start<end,步长为正
如果start>end,步长为负
s = '2008-12-8'
print(s[0:4:1]) # 2008
print(s[5:7:1]) # 12
print(s[8::1]) # 8
# 切片提取片段
s = '0123456789'
print(s[1:8:3]) # 147
print(s[:5:]) # 01234,取前5个数字
print(s[len(s) - 5::]) # 56789,取后5个数字
print(s[-5::]) # 56789,取后5个数字
print(s[::-1]) # 9876543210 字符串翻转
print(s[-6:-2:1]) # 4567
print(s[-2:-6:-1]) # 8765
# 切片提取并替换
s = '0123456789'
res = s[1:8:3] # 147
for ch in res: # 1 4 7
s = s.replace(ch, '*')
print(s)
字符串断言
断言:判断对错
s = 'abc'
print(s.isdigit()) # 是否只包含数字
print(s.isalpha()) # 是否只包含中文 日文 韩文 +英文字母等
print(s.isalnum()) # 是否只包含中文 日文 韩文 +英文字母+数字
print(s.isascii()) # 是否只包含字母+数字+空格+特殊符号等
print(s.islower()) # 存在的字母是否全小写
print(s.isupper()) # 存在的字母是否全大写
print(s.isspace()) # 是否只包含空格
# 判断字符串必须包含字母、数字、特殊符号(@#$%^&*!)
s = 'ab$12#cd'
flag1 = False # 字母
flag2 = False # 数字
flag3 = False # 特殊符号
flag4 = len(s) >= 8
for ch in s:
if ch.isascii() and ch.isalpha():
flag1 = True
if ch.isdigit():
flag2 = True
if ch in '@#$%^&*!':
flag3 = True
print(flag1 and flag2 and flag3 and flag4)