Python基础——字符串操作

本文详细介绍了Python中字符串的常用操作,包括字符串格式化(占位符、f-string和format方法)、编码解码、数据验证、拼接去重、以及正则表达式的re模块应用,如match、search、sub和split等。
摘要由CSDN通过智能技术生成

目录

一、字符串的常用操作

 二、格式化字符串的三种方式

 一、占位符

二、f-string

三、字符串的format方法

三、字符串的编码和解码

四、字符串的数据验证

五、字符串的处理

一、字符串的拼接

二、字符串的去重

 六、正则表达式

re模块

 七、总结


一、字符串的常用操作

(1)

d99fb04ce8e2486ebabc1f07807717d5.png

大小写只对英文字母有效,其他的不变

807335b7a7f047ce87cac98f49de2432.png

s1='Hello_BB8639757'
print(s1.lower(),s1.upper())

#split()
e_mail='yorelee@163.com'
lst=e_mail.split('@')
print('邮箱名:',lst[0],'邮件服务器域名:',lst[1])

#子串出现个数
print(s1.count("o"))

#检索
print(s1.find('4'))#没找到返回-1 (正向索引哦)
print('Hello_BB8639757'.find('l'))
print(s1.index('l'))
#print('Hello_BB8639757'.index('4'))#没找到会报错

#判断前缀后缀
print('I love yore'.endswith('yore'))
print('I love yore'.endswith('qq'))
print('I love yore'.startswith('I '))
print('I love yore'.startswith('qq'))
'''
hello_bb8639757 HELLO_BB8639757
邮箱名: yorelee 邮件服务器域名: 163.com
1
-1
2
2
True
False
True
False
'''

(2)

a1ce336f02b24e3eb6a301f6f10b24c6.png

replace有三个参数,最后一个参数是替换几次。默认为替换所有。

center返回的是一个字符串。

strip(chars) 去掉的是chars里面的字符,与顺序无关。

s='Hello world'
print(s.replace('l','你好呀',2))
print(s.replace('l','你好呀',1))
print(s.replace('l','你好呀'))

print(s.center(20))
print(s.center(20,'*'))

s='  Hello world   '
print(s.strip())#默认去掉空字符
print(s.strip(' '))
print(s.lstrip())
print(s.rstrip())
print(s.rstrip().rstrip('lrd'))
print(s.rstrip().rstrip('wod'))
'''
He你好呀你好呀o world
He你好呀lo world
He你好呀你好呀o wor你好呀d
    Hello world     
****Hello world*****
Hello world
Hello world
Hello world   
  Hello world
  Hello wo
  Hello worl
'''
lst=['我给你的爱','写在西元前']
s='那已风化千年的诗篇'
y=tuple(['深埋在美索不达米亚平原','噢噢~'])
print(','.join(lst),','.join(s),','.join(y),sep='\n')
'''
我给你的爱,写在西元前
那,已,风,化,千,年,的,诗,篇
深埋在美索不达米亚平原,噢噢~
'''

 二、格式化字符串的三种方式

ca7e491e191d4dc8916aa3692169ad09.png

简化不同数据类型之间的连接操作。

这里只列举出常用的占位符。

 一、占位符

name='马冬梅'
age=18
score=98.5
print('姓名:%s,年龄:%d,成绩:%.1f'%(name,age,score))#只有一个时,可以不用括号
'''
姓名:马冬梅,年龄:18,成绩:98.5
'''

二、f-string

name='马冬梅'
age=18
score=98.5
print(f'姓名:{name},年龄:{age},成绩:{score}')
'''
姓名:马冬梅,年龄:18,成绩:98.5
'''

三、字符串的format方法

字符串中的{x},数字x对应了format()中位置参数。

name='马冬梅'
age=18
score=98.5
print('姓名:{0},年龄:{1},成绩:{2}'.format(name,age,score))
print('姓名:{2},年龄:{0},成绩:{1}'.format(age,score,name))
'''
姓名:马冬梅,年龄:18,成绩:98.5
姓名:马冬梅,年龄:18,成绩:98.5
'''

4a053a0517bb4181b93ecf6562c65bf0.png

区分内置函数format的功能和调用。

详细格式

a27426f2feed41b68a4ad42ddb9189bf.png

{参数位置:填充字符+对齐方式+宽度} (填充字符只能是单个字符,参数只能是字符串)

name='yorelee'
print('{0:-^20}'.format(name))
#等价于print(format(name,'-^20'))
#等价于print(name.center(20,'-'))
'''
------yorelee-------
'''

{参数位置:,} (参数只能是数字,可以是整型也可以是浮点型)

print('{0:,}'.format(8639757888))
print('{0:,}'.format(8639757888.8888))
'''
8,639,757,888
8,639,757,888.8888
'''

{参数位置: .nf} (参数只能是数字,表示小数部分精度)

{参数位置: .n}(参数是字符串,表示最大输出长度)

print('{0:.5f}'.format(8639757888))
print('{0:.5f}'.format(8639757888.8888))
print('{0:.2f}'.format(8639757888.8888))
print('{0:.2}'.format('8639757888.8888'))
print('{0:.210}'.format('8639757888.8888'))
'''
8639757888.00000
8639757888.88880
8639757888.89
86
8639757888.8888
'''
a=425
print('二进制:{0:b},八进制:{0:o},十六进制:{0:x}'.format(a))

b=3.1415926535
print('{0:.2f},{0:.2e},{0:.2E},{0:.2%}'.format(b))

三、字符串的编码和解码

a43a1ef8cb084d67919f1d0ac6f357b4.png

cc4edd8f16b94208b417c98d4b41a8a1.png

strict是严格的,出错则抛出异常

ignore忽略出错

replace用?代替无法转换的字符。

02e6c75ea6e8492bae7c9feede1c5821.png

四、字符串的数据验证

816cb66bb1e341caa3c2dd0a1b74a4e2.png

isnumeric()可以识别中文的数字 一二三四这种,罗马数字,阿拉伯数字。它是按字符看的!

print('123'.isdigit())#True
print('十'.isdigit())#False
print('0b1010'.isdigit())#False
print('Ⅰ'.isdigit())#False
print('-'*50)
print('123'.isnumeric())#True
print('十壹'.isnumeric())#True
print('ⅠⅠⅠ'.isnumeric())#True
print('0b1010'.isnumeric())#False
print('-'*50)
print('hello你好'.isalpha())#True
print('hello你好123'.isalpha()) #False
print('hello你好123?'.isalpha())#False
print('hello你好123Ⅰ'.isalpha())#False
print('hello你好123'.isalnum())#True
print('hello你好123?'.isalnum())#False
print('hello你好123Ⅰ壹'.isalnum())#True
print('-'*50)
print('Helloworld'.islower())#False
print('helloworld'.islower())#True
print('helloworld你好123?'.islower())#True
print('Ⅰ'.islower())#False 罗马字符是大写
print('Ⅰ'.isupper())#True
print('helloworld你好123'.upper())
print('-'*50)
print('HelloWorld'.istitle())#False
print('Helloworld'.istitle())#True
print('Hello World'.istitle())#True 用空格分隔单词
print('HEl'.istitle())#False 是否只有首字母大写

五、字符串的处理

一、字符串的拼接

236db7db3009427ea09127f72714c6fa.png

s1='hello'
s2='world'
#+号连接
print(s1+s2)
#join连接
print(''.join([s1,s2]))
print(',你好呀,'.join([s1,s2,s1]))
#直接拼接 只有俩常字符串可以
s3='hello''world'
print('hello''world')

#格式化字符串
print('%s%s'%(s1,s2))
print(f'{s1}{s2}')
print('{0}{1}'.format(s1,s2))
'''
helloworld
helloworld
hello,你好呀,world,你好呀,hello
helloworld
helloworld
helloworld
helloworld
'''

二、字符串的去重

(1)字符串拼接+not in

new_s=''
for item in s:
    if item not in new_s:
        new_s+=item
print(new_s)

(2)使用索引+not in (本质是一样的,就是for循环遍历的时候不一样而已)

new_s=''
for i in range(len(s))
    if s[i] not in new_s:
        new_s+=s[i]
print(new_s)

(3)通过集合去重+列表排序

new_s=set(s)
lst=list(new_s)
lst.sort(key=s.index)
#key给定参数 s.index 是指lst中的元素传入函数s.index() 返回值作为排序值
new_s=''.join(lst)

 六、正则表达式

a032438237ea46759d4fb2beb2385dde.png

这里只列出了一部分。这里的匹配指的是

2c5003049e564d8eaa257d8f42e31561.png

6da72cb96f2b409baf57de779d235171.png

和编译原理里面的正则表达式有点像。

re模块

b747ecf5bd874e8bb4ea373e89f30837.png

4e7a06d609b64f4d86834fb8d93f82e3.png

match

6e2006946d2f41539d4104e1c57a2339.png

8aabf6cc32eb4e568788b1a872555e05.png


search和findall

search和match的区别在于,search是从整个字符串中找第一个,而match只在开始起始位置找。findall是在整个字符串中找出所有。

77cc55545d5246458f2537c0fba68e32.png

a1d43182be5f4bf792cf585f36dec689.png


55f081cab45244fd9d9ff9103ab92902.png

b6f4bce8dfa74eb2b0f7b7a588ae92a1.png


sub和split

ed69b74095ad42159d23e418787bda71.png

ed6ab457c3c9409f83e7de063e86b4e2.png

 七、总结

bb58f37b340d442b8239af18b39ba601.png

e96eac1f9579480b8da30449b46ce1b1.png

  • 11
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Yorelee.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值