五、Python——字符串

字符串也是不可变对象

1.创建字符串

  • 使用单引号、双引号、三引号定义字符串
# 普通字符串定义
s1 = '123'
s2 = "abc"
s3 = """123
'abc'
"ABC"
"""
s4 = '''123
"abc"
'ABC'
'''
  • 字符串前面添加一个字母前缀来表示特殊含义,r/R代表raw:原义字符串或反转字符串,b代表bin,即二进制字符串
# 反转义字符串
s5 = r'c:\program files\python.exe'
s6 = R'c:\program files\python.exe'
# 二进制字符串
s7 = b'hello python'

2.检索字符串

  • 通过索引下标检索
s = '123abc!@# Hello Python'
print(f'字符串s => {s}')  # 123abc!@# Hello Python
print(f's[1] => {s[1]}') # 2
print(f's[6:] => {s[6:]}')   # !@# Hello Python
print(f's[6:-1] => {s[6:-1]}')   # !@# Hello Python
print(f's[:-3] => {s[:-3]}')  # Hello Pyt

3.删除字符串

s = 'Hello Python!'
del s

4.转义字符

在这里插入图片描述
需要强制换行时,可以在字符串中显式添加\r\n;字符串中包含引号时,为了不与外层的定义引号冲突,可以用反斜杠(\)进行转义

print('强制换行\r\n我是新行')
print('tab字段1\ttab字段2')
print('单引号字符串包含\'单引号')
print("双引号字符串包含\"双引号")
print("转义反斜杠本身\\,取消第二个反斜杠的转义功能")
print('字符串包括空格\000 空格后内容')
print('八进制换行表示法\012 我是新行')
print('十六进制回车表示法\x0a我是新行')
print('其他字符转义\\为字符本身')
# 执行结果
强制换行
我是新行
tab字段1 tab字段2
单引号字符串包含'单引号
双引号字符串包含"双引号
转义反斜杠本身\,取消第二个反斜杠的转义功能
字符串包括空格 空格后内容
八进制换行表示法
我是新行
十六进制回车表示法
我是新行
其他字符转义\为字符本身

5.字符串运算

  • 查找、拼接、截断、重复
s = "Hello Python"
print("s内容 => ", s)
s2 = "Python"
print("s2 内容 => ", s2)
print("字符串查找:s2 in s => ", (s2 in s))  # True
s3 = "world"
print("s3 内容 => ", s3)
print("字符串查找:s3 not in s => ", (s3 not in s))  # True
print("字符串拼接:s2 + s3 => ", s2 + s3)  # Pythonworld
print("字符串截断:s[:5] => ", s[:5])   # Hello
print("重复字符串:s * 3 => ", s * 3)   # Hello PythonHello PythonHello Python

6.字符串格式化

  • %-formatting形式的格式化通过%格式符来连接字符串和格式化参数,%{格式化占位符}用于占位,最后会被格式化参数中对应的内容所替换,而替换的规则分为按参数位置替换和按关键字替换。
# 按参数位置替换
print('你好 %s' % 'Python')
print('我的名字叫%s,今年%s岁,上%s年级' % ('小明', 6, '一'))
# 执行结果
# 你好 Python
# 我的名字叫小明,今年 6 岁,上一年级


# 按关键字替换
print('你好 %(name)s' % {'name': 'Python'})
d = {'name': '小明', 'age': 6, 'grade': '一'}
print('我的名字叫%(name)s,今年%(age)s岁,上%(grade)s年级' % d)
# 执行结果
# 你好 Python
# 我的名字叫小明,今年 6 岁,上一年级
  • 其余类型占位
# 完整的格式化占位的语法
%[(name)][flags][width][.precision]typecode
参数作用
%和typecode必需部分
(name)用于关键字参数化
(flags)用于指定对齐方式
(width)用于指定占用宽度
(.precision)用于指定小数点的保留位数
typecode支持的类型码如下图所示

在这里插入图片描述
字符串格式化类型码使用实例:

print('%%s 格式化"Python":%s' % "Python") # %s格式化“Python”:Python
print('%%s 格式化10:%s' % 10)  # %s格式化10:10
print('%%s 格式化3.14:%s' % 3.14)  # %s格式化3.14:3.14
print(r'%%r 格式化“\r\n”:%r' % "\r\n")  # %r格式化“\r\n”:'\r\n'
print('%%c 格式化65:%c' % 65)  # A
print('%%o 格式化10:%o' % 10)  # 12
print('%%x 格式化10:%x' % 10)  # a
print('%%d 格式化0o10:%d' % 0o10)  # 8
print('%%d 格式化0x10:%d' % 0x10)  # 16
print('%%f 格式化10:%f' % 10)  # 10.000000
  • str.format方法格式化
# 按参数位置替换
print('你好 {}'.format('Python'))  # 不加索引,按默认位置对应
print('我的名字叫{1},今年{0}岁,上{2}年级,会{0}种语言'.format(6, '小明', '一'))
# 执行结果
# 你好 Python
# 我的名字叫小明,今年6岁,上一年级,会6种语言


# 按关键字替换
d = ['name': '小明', 'cnt': 6, 'grade': '一']  # 列表:顺序不能乱
print('我的名字叫{},今年{}岁,上{}年级,会{}种语言'.format(*d))


print('你好 {name}'.format(name='Python'))
d = {'name': '小明', 'cnt': 6, 'grade': '一'}  # 字典:顺序可以乱
print('我的名字叫{name},今年{cnt}岁,上{grade}年级,会{cnt}种语言'.format(**d))
# 执行结果
# 你好 Python
# 我的名字叫小明,今年6岁,上一年级,会6种语言

7.分割字符串:split、rsplit、partition

s = '1234,5678,910,aBcD,'
print(f'原字符串 => {s}')   # 1234,5678,910,aBcD,

print(f'split方法:(以,为分隔符对字符串进行分割)') # 切割后为列表
print(f's.split(",") => {s.split(",")}')  # ['1234','5678','910','aBcD','']
print(s.split(",",2)) # ['1234','5678','910,aBcD,']  分割两次后不再分割
# rsplit()同理,从右边开始分割


# partition :指定一个字符串作为分隔符,分为:前 分隔符 后
print(s.partition('8'))  # '1234,567','8',',910,abcd,'

# 获取文件名和后缀
file_name = '2022.3.4招聘.mp4'
print(file_name.rpartition('.'))  # 最好从后开始

8.查找字符串下标:find、index

s = '1234,5678,910,aBcD,'
print(f'原字符串 => {s}')   # 1234,5678,910,aBcD,

print(f'find|index方法:(自左向右查找123|000在字符串中首次出现的位置)')
print(f's.find("123") => {s.find("123")}')  # 0     若字符不存在不会报错
print(f's.index("123") => {s.index("123")}') # 0   若字符不存在会报错
print(f's.find("000") => {s.find("000")}')   # -1
# print(f's.index("000") => {s.index("000")}') # 抛出异常

9.判定字符串开头、结尾:startswith、endswith

s = '1234,5678,910,aBcD,'
print(f'原字符串 => {s}')   # 1234,5678,910,aBcD,

print(f'startswith方法:(检查字符串是否以123|234开头)')
print(f's.startswith("123") => {s.startswith("123")}') # True
print(f's.startswith("234") => {s.startswith("234")}')  # False

print(f'endswith方法:(检查字符串是否以910|123结尾)')
print(f's.endswith("910") => {s.endswith("910")}')  # False
print(f's.endswith("123") => {s.endswith("123")}')  # False

10.统计字符串出现次数:count

s = '1234,5678,910,aBcD,'
print(f'原字符串 => {s}')   # 1234,5678,910,aBcD,

print(f'count 方法:(统计字符串中123出现的次数)') 
print(f's.count("123") => {s.count("123")}')     # 1
print(f's.count(",") => {s.count(",")}')       # 4

11.字符串空格:ljust、rjust、center、strip

  • 补充空格
# 空格显示
# ljust(len):指定长度显示,不够用空格补充
print('hello'.ljust(10)) # hello5个空格
print('hello'.ljust(10,'+'))  # hello+++++
print('hello'.rjust(10,'-'))  # -----hello
print('hello'.center(10,'*'))  # ***hello**
  • 去掉空格
print('    hello   '.lstrip())  #hello    
print('    hello   '.rstrip())  #    hello
print('    hello   '.strip())    #hello  两边空格去掉
print('++++hello+++'.lstrip('+'))  #hello+++

12.列表转字符串

print(f'join方法:(以,为连接符连接字符串列表)')
print(f'",".join(["1", "2", "3"]) => {",".join(["1", "2", "3"])}')  # 1,2,3

s = ['ab','cd']
print('-'.join(s)) # ab-cd
print('*'.join('sxl'))   # s*x*l   sxl内容为可迭代对象
print('+'.join(('yes','ok')))  # yes+ok

13.字符编码:chr、ord

print(ord('a'))  # 97
print(chr(65))   # A

GBK:国标扩,汉字占两个字节
BIG5:繁体中文
utf-8:统一编码,汉字占三个字节

14.字符串其它方法

s = '1234,5678,910,aBcD,'
print(f'原字符串 => {s}')   # 1234,5678,910,aBcD,

print(f'encode|decode方法:(对字符串进行utf-8编码)')
print(f's.encode("utf-8") => {s.encode("utf-8")}') # b'1234,5678,910,aBcD,'
print(f'b"123".decode("utf-8") => {b"123".decode("utf-8")}')  # 123


print(f'replace方法:(把字符串中的,替换为_)')
print(f's.replace(",", "_") => {s.replace(",", "_")}')  # 1234_5678_910_aBcD_



print(f'strip方法:(移除字符串首尾位置的,)')
print(f's.strip(",") => {s.strip(",")}')  # 1234,5678,910,aBcD

print(f'lower方法:(把字符串中的字母都转换为小写形式)')
print(f's.lower() => {s.lower()}')  # 1234,5678,910,abcd,

print(f'upper方法:(把字符串中的字母都转换为大写形式)')
print(f's.upper() => {s.upper()}')  # 1234,5678,910,ABCD,

# capitalize:第一个字母大写,无论换行还是.
print('hello'.capitalize()) # Hello

# title:每个单词首字母大写
print('good morning'.title())  # Good Morning

print(f'zfill方法:(字符串左边补零直到满足指定长度:20)')
print(f's.zfill(20) => {s.zfill(20)}')  # 01234,5678,910,aBcD,
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值