Python:字符串用法

Python:字符串用法,第1张

文章目录
  • 字符串的常用 *** 作
    • 字符串的查询 *** 作方法
    • 字符串的大小写转换 *** 作方法
    • 字符串内容对齐 *** 作的方法
    • 字符串劈分的方法
    • 判断字符串的方法
    • 字符串 *** 作的其他方法
    • 字符串的比较 *** 作
    • 字符串的切片 *** 作
    • 格式化字符串
    • 字符串的编码转换
    • 总结

字符串的常用 *** 作 字符串的查询 *** 作方法
方法名称作用
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

字符串的大小写转换 *** 作方法
方法名称作用
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

字符串的切片 *** 作

字符串是不可变类型

  • 不具备增、删、改等 *** 作
  • 切片 *** 作将产生新的对象
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

格式化字符串

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

  • %占位符
    例:
    ‘我的名字叫:%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位是小数
字符串的编码转换

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

- 编码与解码的方式

  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'))  #天涯共此时
总结

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/942500.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-18
下一篇 2022-05-18

发表评论

登录后才能评论

评论列表(0条)

保存