Python:字符串用法

简介: Python:字符串用法

字符串的常用操作


字符串的查询操作方法

方法名称 作用
index() 查找子串substr第一次出现的位置,如果查找的子串不存在时,则抛出ValueError
rindex() 查找子串substr最后一次出现的位置,如果查找的子串不存在时,则抛出ValueError
find() 查找子串substr第一次出现的位置,如果查找的子串不存在时,则返回-1
rfind() 查找子串substr最后一次出现的位置,如果查找的子串不存在时,则返回-1


s = 'hello,hello'
print(s.index('lo'))   # 3
print(s.find('lo'))    # 3
print(s.rindex('lo'))  # 9
print(s.rfind('lo'))   # 9
# print(s.index('k'))   # ValueError: substring not found
print(s.find('k'))      # -1
# print(s.rindex('k'))   # ValueError: substring not found
print(s.rfind('k'))      # -1

6939b0e9b63e491ca9d6a6460fa7fd48.png


字符串的大小写转换操作方法

方法名称 作用
upper() 把字符串中所有字符都转换成大写字母
lower() 把字符串中所有字符都转换成小写字母
swapcase() 把字符串中所有大写字母转换为小写字母,把所有小写字母转换为大写字母
capitalize() 把第一个字符转换为大写,把其余字符转换为小写
title() 把每个单词的第一个字符转换为大写,把每个单词的剩余字符转换为小写


s='hello,python'
a=s.upper()     # 转换成大写之后,会产生一个新的字符串对象
print(a,id(a))  #HELLO,PYTHON 1792337784432
print(s,id(s))  #hello,python 1792337784240
b=s.lower()     # 转换之后,会产生一个新的字符串对象
print(b,id(b))  #hello,python 1792338138864
print(s,id(s))  #hello,python 1792337784240
print(b==s)     #True
print(b is s)   #False
s2='hello,Python'
print(s.swapcase())  # HELLO,PYTHON
print(s.title())     # Hello,Python


字符串内容对齐操作的方法

方法名称 作用
center() 居中对齐,第1个参数指定宽度,第2个参数指定填充符,第2个参数是可选的,默认是空格,如果设置宽度小于实际宽度则返回原字符串
ljust() 左对齐,第1个参数指定宽度,第2个参数指定填充符,第2个参数是可选的,默认是空格,如果设置宽度小于实际宽度则返回原字符串
rjust() 右对齐,第1个参数指定宽度,第2个参数指定填充符,第2个参数是可选的,默认是空格,如果设置宽度小于实际宽度则返回原字符串
zfill() 右对齐,左边用0填充,该方法只接收一个参数,用于指定字符串的宽度,如果指定的宽度小于等于字符串的长度,返回字符串本身


s='hello,Python'
'''剧居中对齐'''
print(s.center(20,'*'))   # ****hello,Python****
'''左对齐'''
print(s.ljust(20,'*'))    # hello,Python********
print(s.ljust(10))        # hello,Python
print(s.ljust(20))        # hello,Python        
'''右对齐,使用0填充'''
print(s.zfill(20))        # 00000000hello,Python
print(s.zfill(10))        # hello,Python
print('-8910'.zfill(8))   #-0008910


字符串劈分的方法

方法名称 作用
split() 从字符串的左边开始劈分,默认的劈分字符是空格字符串,返回的值都是一个列表
split() 以通过参数sep指定劈分字符串似的劈分符
split() 通过参数maxsplit指定劈分字符串时的最大劈分次数,在经过最大次劈分之后,剩余的子串会单独作为一部分
rsplit() 从字符串的右边开始劈分,默认的劈分字符是空格字符串,返回的值都是一个列表
rsplit() 以通过参数sep指定劈分字符串似的劈分符
rsplit() 通过参数maxsplit指定劈分字符串时的最大劈分次数,在经过最大次劈分之后,剩余的子串会单独作为一部分


s='hello world Python'
lst=s.split()
print(lst)                   #['hello', 'world', 'Python']
s1='hello|world|Python'
print(s1.split(sep='|'))     #['hello', 'world', 'Python']
print(s1.split())            #['hello|world|Python']  split()默认劈分符为空格
print(s1.split(sep='|',maxsplit=1))    #['hello', 'world|Python']
'''rsplit()从右侧开始劈分'''
print(s.rsplit())       #['hello', 'world', 'Python']
print(s1.rsplit('|'))   #['hello', 'world', 'Python']
print(s1.rsplit(sep='|',maxsplit=1))   #['hello|world', 'Python']


判断字符串的方法

方法名称 作用
isidentifier() 判断指定的字符串是不是合法的标识符
isspace() 判断指定的字符串是否全部由空白字符组成(回车、换行、水平制表符)
isalpha() 判断指定的字符串是否全部由字母组成
isdecimal() 判断指定的字符串是否全部由十进制的数字组成
isnumeric() 判断指定的字符串是否全部由数字组成
isalnum() 判断指定的字符串是否全部由字母和数字组成


1、合法的字符串是“字母、数字、下划线_”,逗号不包含在内

s='hello,python'
print('1.',s.isidentifier())          #1. False
print('2.','hello'.isidentifier())    #2. True
print('3.','张三_'.isidentifier())    #3. True
print('4.','张三_123'.isidentifier()) #4. True
print('5.','\t'.isspace())            #5. True
print('6.','abc'.isalpha())           #6. True
print('7.','张三'.isalpha())          #7. True
print('8.','张三1'.isalpha())         #8. False
print('9.','123'.isdecimal())         #9. True
print('10.','123四'.isdecimal())      #10. False
print('11.','ⅡⅡⅢ'.isdecimal())     #11. False
print('12.','123'.isnumeric())       #12. True
print('13.','123四'.isnumeric())     #13. True
print('14.','ⅡⅡⅢ'.isnumeric())    #14. True
print('15.','abc1'.isalnum())       #15. True
print('16.','张三123'.isalnum())    #16. True
print('17.','abc!'.isalnum())       #17. False


字符串操作的其他方法

功能 方法名称 作用
字符串替换 replace() 第1个参数指定被替换的子串,第2个参数指定替换子串的字符串,该方法返回替换后得到的字符串,替换前的字符串不发生变化,调用该方法是可以通过第3个参数指定最大替换次数
字符串的合并 join() 将列表或元组中的字符串合并成一个字符串


s='hello,Python'
print(s.replace('Python','Java'))     #hello,Java
s1='hello,python,python,python'
print(s1.replace('python','java',2))  #hello,java,java,python
lst=['hello','java','python']
print('|'.join(lst))   #hello|java|python
print(''.join(lst))    #hellojavapython
t=('hello','python','java')
print(''.join(t))          #hellopythonjava
print('*'.join('python'))  #p*y*t*h*o*n


字符串的比较操作


  • 运算符:>,>=,<,<=,==,!=
  • 比较规则:首次比较两个字符串中的第一个字符,如果相等则继续比较下一个字符,依次比较下去,直到两个字符串中的字符不相等时,其比较结果就是两个字符串的比较结果,两个字符串中的所有后续字符将不再被比较。
  • 比较原理:两个字符进行比较时,比较的是其ordinal value (原始值),调用内置函数ord可以得到指定字符的ordinal value。与内置函数ord对应的是内置函数chr,调用内置函数chr时指定ordinal value 可以得到其对应的字符。
print('apple'>'app')      #True
print('apple'>'banana')   #False
print(ord('a'),ord('b'))  #97 98
print(ord('是'))          #26159
print(chr(97),chr(98))    #a b
print(chr(26159))         #是
'''
== 与 is 的区别
==:比较的是value
is:比较的是id是否相等
'''
a=b='python'
c='python'
print(a==b)   #True
print(b==c)   #True
print(a is b)  #True
print(a is c)  #True
print(id(a))   #2093415080560
print(id(b))   #2093415080560
print(id(c))   #2093415080560


字符串的切片操作


字符串是不可变类型

  • 不具备增、删、改等操作
  • 切片操作将产生新的对象

8ded32268ba84093aa2fdc8a53c6d1df.png

s='hello,Python'
s1=s[:5]     #由于没有指定起始位置,所以从0开始切
s2=s[6:]     #由于没有指定结束位置,所以切到字符串的最后一个元素
s3='!'
newstr=s1+s2+s3
print(s1)       #hello
print(s2)       #Python
print(newstr)   #helloPython!
'''切片[start:end:step]'''
print(s[1:5:1])   #ello   从1开始截到5(不包含5),步长为1
print(s[::2])     #hloPto   默认从0开始,没有写结束,默认到字符串的最后一个元素,步长为2,两个元素质检的索引间隔为2
print(s[::-1])    #nohtyP,olleh   默认从字符串的
print(s[-6::1])   #Python

e7ddcdf3c13b4c44aebe010d4f844078.png


格式化字符串


格式化字符串的两种方式:

  • %占位符
    例:

‘我的名字叫:%s,今年%d岁了’ % (name,age)

说明:

‘我的名字叫:%s,今年%d岁了’——定义的格式化字符串;

%——固定符号

(name,age)——占位符实际值

  • {}做占位符
    例:
    ‘我的名字叫:{0},今年{1}岁了,我真的叫{0}’.format(name,age)
# 格式化字符串
#1、 % 占位符
name = '张三'
age = 20
print('我叫%s,今年%d岁' % (name,age))        # 我叫张三,今年20岁
# 2、 {}
print('我叫{0},今年{1}岁'.format(name,age))  # 我叫张三,今年20岁
# 3、 f-string
print(f'我叫{name},今年{age}岁')             # 我叫张三,今年20岁


# 精度和宽度——%
print('%10d' % 99)           #        99;      10表示的是宽度
print('%.3f' % 3.1415926)    #3.142;           3表示小数点后3位
# 同时表示宽度和精度
print('%10.3f' % 3.1415926)  #     3.142;      一共总宽度为10.小数点后保留3位
print('hellohello')          #hellohello;
# 精度和宽度——{}
print('{0:.3}'.format(3.1415926))    #3.14;       .3表示一共是3位数;{}中0表示占位符的顺序
print('{0:.3f}'.format(3.1415926))   #3.142;      .3f表示保留3位小数;{}中0可以省略
print('{:10.3f}'.format(3.1415926))  #     3.142;  同时设置宽度和精度,一共是10位,3位是小数


字符串的编码转换


- 为什么需要字符串的编码转换?

ac203bbd6bb044449be08736d38ed76a.png

- 编码与解码的方式

  1. 编码:将字符串转换为二进制数据(bytes)
  2. 解码:将bytes类型的数据转换成字符串类型
s = '天涯共此时'
#编码
print(s.encode(encoding='GBK'))   #b'\xcc\xec\xd1\xc4\xb9\xb2\xb4\xcb\xca\xb1'  ——第一个b表示二进制
#在GBK这种编码格式中,一个中文占两个字符;
print(s.encode(encoding='UTF-8'))  #b'\xe5\xa4\xa9\xe6\xb6\xaf\xe5\x85\xb1\xe6\xad\xa4\xe6\x97\xb6'
#在UTF-8这种编码格式中,一个中文占三个字符
#解码
#byte代表就是一个二进制数据(字节类型的数据)
byte=s.encode(encoding='GBK')       #编码
print(byte.decode(encoding='GBK'))  #解码  天涯共此时
# 编码和解码格式必须相同
byte=s.encode(encoding='UTF-8')
print(byte.decode(encoding='UTF-8'))  #天涯共此时


总结

353b8531b42e418597ff56efb40b172c.png

相关文章
|
23天前
|
Python
Python中的f-string:更简洁的字符串格式化
Python中的f-string:更简洁的字符串格式化
185 92
|
1月前
|
索引 Python
python 字符串的所有基础知识
python 字符串的所有基础知识
174 0
|
1月前
|
Python
Python字符串center()方法详解 - 实现字符串居中对齐的完整指南
Python的`center()`方法用于将字符串居中,并通过指定宽度和填充字符美化输出格式,常用于文本对齐、标题及表格设计。
|
2月前
|
PHP Python
Python format()函数高级字符串格式化详解
在 Python 中,字符串格式化是一个重要的主题,format() 函数作为一种灵活且强大的字符串格式化方法,被广泛应用。format() 函数不仅能实现基本的插入变量,还支持更多高级的格式化功能,包括数字格式、对齐、填充、日期时间格式、嵌套字段等。 今天我们将深入解析 format() 函数的高级用法,帮助你在实际编程中更高效地处理字符串格式化。
236 0
|
3月前
|
Python
Python f-strings:让字符串格式化更简洁高效!
Python f-strings:让字符串格式化更简洁高效!
218 81
|
3月前
|
Python
Python字符串格式化利器:f-strings入门指南
Python字符串格式化利器:f-strings入门指南
187 80
|
3月前
|
Python
Python高效字符串格式化:f-strings的魅力
Python高效字符串格式化:f-strings的魅力
161 80
|
26天前
|
Go 调度 Python
Golang协程和Python协程用法上的那些“不一样”
本文对比了 Python 和 Go 语言中协程的区别,重点分析了调度机制和执行方式的不同。Go 的协程(goroutine)由运行时自动调度,启动后立即执行;而 Python 协程需通过 await 显式调度,依赖事件循环。文中通过代码示例展示了两种协程的实际运行效果。
|
5月前
|
移动开发 自然语言处理 Linux
Python中r前缀:原始字符串的魔法解析
本文深入解析Python中字符串的r前缀(原始字符串)的设计原理与应用场景。首先分析传统字符串转义机制的局限性,如“反斜杠地狱”问题;接着阐述原始字符串的工作机制,包括语法定义、与三引号结合的用法及特殊场景处理。文章重点探讨其在正则表达式、文件路径和多语言文本处理中的核心应用,并分享动态构建、混合模式编程等进阶技巧。同时纠正常见误区,展望未来改进方向,帮助开发者更好地理解和使用这一特性,提升代码可读性和维护性。
293 0

热门文章

最新文章

推荐镜像

更多