Python-基础 (六)

发布于:2025-09-08 ⋅ 阅读:(18) ⋅ 点赞:(0)

一:字符串以及正则表达式

二:字符串的常用操作

字符串是python中不可变的数据类型

#1:大小写转换
s1 = 'HelloWorld'
new_s1 = s1.lower()
print(new_s1)

new_s3 = new_s1.upper()
print(new_s3)

#2:字符串的分隔
e_mail = 'ysj@128.com'
lst = e_mail.split('@')
print('邮箱名:',lst[0],'邮箱服务器域名:',lst[1])

#3:
print(s1.count('o'))

#4:检索操作
print(s1.find('O'))  #o在字符串s1中首次出现的位置
print(s1.find('p'))  #-1,没有找到

#
print(s1.index('o'))
print(s1.index('p'))  #找不到,报错


#判断前缀和后缀
print(s1.startswith('H'))  #True
print(s1.startswith('p'))  #False

print('demo.py'.endswith('.py'))  #True
print('text.txt'.endswith('.txt')) #True

#1:替换
word = 'HelloWord'
new_word = word.replace('o','你好',1)
print(new_word)


#2:宽度范围居中
print(word.center(20))


#3:去掉字符串左右的空格
h = '  hello   word'
print(h.strip())
print(h.lstrip())  #去除字符串左侧的空格
print(h.rstrip())  #去除字符串右侧的空格

#4;去掉指定的字符(与字符顺序无关,包含即可)
g = 'dl_HelloWord'
print(g.strip('ld'))
print(g.lstrip('ld'))
print(g.rstrip('ld'))




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

连接各种数据类型

#1:使用占位符进行格式化
name = '马冬梅'
age = 18
score = 98.5
print('姓名:%s,年龄:%d,成绩:%f' %(name,age,score))
print('姓名:%s,年龄:%d,成绩:%.1f' %(name,age,score))


#2:f-string
print(f'姓名:{name},年龄:{age},成绩:{score}')

#3:使用字符串的format方法(0,1,2对应是format里面的顺序)
print('姓名:{0},年龄:{1},成绩:{2}'.format(name,age,score))
print('姓名:{2},年龄:{0},成绩:{1}'.format(age,score,name))



网站公告

今日签到

点亮在社区的每一天
去签到