python17 字符串的常用操作

字符串常用方法

代码

'''
字符串常用方法
'''
s = 'i am SyLar, I LOVE YOU'
s1 = s.capitalize()# 首字母变成大写
print(s1)
s2=s.lower() # 全部变成小写
print(s2)
s3= s.upper()#全部变成大写 忽略大小写 推荐用这个
print(s3)

title = 'abc_def_hi'
print('标题:',title.title())

s4 = 'HelloWorld'
print(f'转大写:{s4.upper()}')
print(f'转小写:{s4.lower()}')
# 字符串分隔
e_mail = 'cjh@163.com'
lst = e_mail.split('@')
print(f'字符串分隔-》邮箱名:{lst[0]},服务器域名:{lst[1]}')

# 字符串统计
print(f'字符串统计:{s4.count('o')}')

# 查找,检索操作
print(f'0在字符串中首次出现的位置(索引):{s4.find('o')}')
# 查找不存在的字符,返回-1,和index()的区别是index()没有找到会报错
print(f'p在字符串中首次出现的位置(索引):{s4.find('p')}')

# 判断前缀和后缀
# 方便用于检查前缀和后缀,判断类型
print("StringTest.py".endswith('py'))
print("StringTest.txt".endswith('txt'))#判断是否是文本文件

print(f'是以H开头吗?{s4.startswith('H')}')
print(f'是以P开头吗?{s4.startswith('P')}')

# 替换 replace的最后一个参数是替换次数,默认全部替换
new_s = s4.replace('o','你好')
print(f'替换:{new_s}')
# 替换一次
new_s = s4.replace('o','你好',1)
print(f'替换1:{new_s}')
# 字符串在指定的宽度范围内居中
print(s4.center(20))
# 指定填充字符
print(s4.center(20,"*"))

# 去掉空格
s5 = "   Hello World   "
# 去掉左右空格
print(f'去掉左右空格:{s5.strip()}')
# 去掉左空格
print(f'去掉左空格:{s5.lstrip()}')
# 去掉右空格
print(f'去掉右空格:{s5.rstrip()}')
# 去掉指定的字符
s6 = 'dl-Helloworld'
print(f'去掉指定的字符:{s6.strip('ld')}')#与顺序无关,一个字符一个符去删除的,并不是以ld为一个整体去删除的
print(f'去掉指定的字符->左:{s6.lstrip('ld')}')
print(f'去掉指定的字符->右:{s6.rstrip('ld')}')

# 格式化字符串
# 占位符 %s:字符串格式,%d:十进制整数格式,%f:浮点数格式
name = "stevenChen"
age = 18
score = 98.5
print('占位符->姓名:%s,年龄:%d,成绩:%f' % (name,age,score))
print('占位符->姓名:%s,年龄:%d,成绩:%.1f' % (name,age,score))#%.1f表示保留1位小数
# f-string 3.6所引入的格式化 {}
print(f'f-string->姓名:{name},年龄:{age},成绩:{score}')
# str.format(逗号分隔的参数)方法
print('format->姓名:{0},年龄:{1},成绩:{2}'.format(name,age,score))

# format详细格式控制
s7 = "helloworld"
print('{0:*<20}'.format(s7))#字符串的显示宽度为20,左对齐,空白部分使用*号填充
print('{0:*>20}'.format(s7))#字符串的显示宽度为20,右对齐,空白部分使用*号填充
print('{0:*^20}'.format(s7))#字符串的显示宽度为20,居中对齐,空白部分使用*号填充
print(s7.center(20,"*"))

# 千位分隔符(只适用于整数和浮点数)
print('千位分隔符_整数:{0:,}'.format(987654321))
print('千位分隔符_浮点数:{0:,}'.format(987654321.7865))
# 浮点数小数部分的精度
#%.1f表示保留1位小数
print('{0:.1f}'.format(3.1415926))
#%.2f表示保留2位小数
print('{0:.2f}'.format(3.1415926))
#%.4f表示保留4位小数
print('{0:.4f}'.format(3.1415926))

# 字符串类型 .表示最大的显示长度
# 最大显示5个字符
print('{0:.5}'.format('helloworld'))
# 整数类型
num = 425
print('二进制:{0:b},十进制:{0:d},八进制:{0:o},十六进制:{0:x},十六进制:{0:X}'.format(num))
# 浮点数类型
num1 = 3.1415926
print('2位小数:{0:.2f},科学计数法:{0:.2E},:{0:.2e},百分比:{0:.2%}'.format(num1))

# 字符串编码和解码 errors=strict/ignore/replace/       strict:严格,ignore:忽略,replace:替换
s10 = '伟大的中国梦'
# 编码 str->bytes
scode = s10.encode(errors='replace')#默认是utf-8,因为utf-8中文占3个字节
print(f'编码utf-8->{scode}')

scode_gbk = s10.encode('gbk',errors='replace')#因为gbk中文占2个字节
print(f'编码gbk->{scode_gbk}')

# 编码中出错问题
s11='耶✌︎︎'
scode1 = s11.encode('gbk',errors='ignore')#ignore:忽略
print(f'编码gbk编码中出错问题——忽略->{scode1}')
# 编不了用?问号替换
scode_gbk_1 = s11.encode('gbk',errors='replace')#replace:替换
print(f'编码gbk编码中出错问题——替换->{scode_gbk_1}')
#编不了会报错:UnicodeEncodeError: 'gbk' codec can't encode character '\u270c' in position 1: illegal multibyte sequence
# scode2 = s11.encode('gbk',errors='strict')#strict:严格
# print(f'编码gbk编码中出错问题2——严格->{scode2}')

# 解码 bytes->str
print(f'解码utf_8:{bytes.decode(scode,'utf-8')}')
print(f'解码gbk:{bytes.decode(scode_gbk,'gbk')}')

# 数据的验证
# 所有的字符是否都是数字(只能是阿拉伯数字)
print(f'所有的字符是否都是数字(只能是阿拉伯数字):{'123'.isdigit()}')# True
print(f'所有的字符是否都是数字(只能是阿拉伯数字):{'一二三'.isdigit()}')# False
print(f'所有的字符是否都是数字(只能是阿拉伯数字):{'0b1010'.isdigit()}')# False
print(f'所有的字符是否都是数字(只能是阿拉伯数字)_罗马数字:{'ⅠⅡⅢⅣⅤ'.isdigit()}')#罗马数字# False
print('_'*50)
# 所有字符都是数字
print(f'所有字符都是数字:{'123'.isnumeric()}')# True
print(f'所有字符都是数字:{'一二三'.isnumeric()}')# True
print(f'所有字符都是数字:{'0b1010'.isnumeric()}')# False
print(f'所有字符都是数字_罗马数字:{'ⅠⅡⅢⅣⅤ'.isnumeric()}')#罗马数字 # True
print(f'所有字符都是数字_人民币:{'壹贰叁肆'.isnumeric()}')#人民币# True
print('_'*50)
# 所有字符都是字母(包括中文字符)
print(f'所有字符都是字母(包括中文字符):{'hello你好'.isalpha()}')#True
print(f'所有字符都是字母(包括中文字符):{'hello你好123'.isalpha()}')# False
print(f'所有字符都是字母(包括中文字符):{'hello你好一二三'.isalpha()}')#True
print(f'所有字符都是字母(包括中文字符):{'hello你好ⅠⅡⅢⅣⅤ'.isalpha()}')# False
print(f'所有字符都是字母(包括中文字符):{'hello你好壹贰叁肆'.isalpha()}')# True
print('_'*50)
# 所有字符都是数字或字母
print(f'所有字符都是数字或字母:{'hello你好'.isalnum()}')#True
print(f'所有字符都是数字或字母:{'hello你好123'.isalnum()}')#True
print(f'所有字符都是数字或字母:{'hello你好一二三'.isalnum()}')#True
print(f'所有字符都是数字或字母:{'hello你好ⅠⅡⅢⅣⅤ'.isalnum()}')#True
print(f'所有字符都是数字或字母:{'hello你好壹贰叁肆'.isalnum()}')# True
print('_'*50)
print('判断字符的大小写')
# 判断字符的大小写,注意:中文又是大写也是小写
print('HelloWorld'.islower())#False
print('helloworld'.islower())#True
print('hello你好'.islower())#True
print('_'*50)
print('HelloWorld'.isupper())#False
print('HELLOWORLD'.isupper())#True
print('HELLO你好'.isupper())#True
print('_'*50)
print('判断首字母是否大写')
# 判断首字母是否大写
print('Hello'.istitle())#True
print('HelloWorld'.istitle())#False
print('Helloworld'.istitle())#True
print('Hello World'.istitle())#True
print('Hello world'.istitle())#False
print('_'*50)
# 判断是否是空白字符
print('判断是否是空白字符')
print('\t'.isspace())#true
print(' '.isspace())#true
print('\n'.isspace())#true

# 字符串拼接
s20 = 'hello'
s21 = 'world'
# 用加号拼接
print(f'用加号拼接:{(s20+s21)}')
# 用空字符串拼接
print(f'用空字符串拼接:{''.join([s20,s21])}')
# 用*号字符串拼接
print(f'用*号字符串拼接:{'*'.join([s20,s21])}')
# 直接拼接
print('hello''world')
# 使用格式化字符串进行拼接,
print('%s%s' % (s20,s21))#%s字符串占位符
print(f'{s20}{s21}')
print('{0}{1}'.format(s20,s21))

# 字符串去重
s30 = 'helloworldhelloworldhelloworldhelloworld'
newS30 = ''
for item in s30:
    if item not in newS30:
        newS30 += item
        print(f'字符串去重:item:{item},newS30:{newS30}')

# 索引去重
newS302 = ''
for index in range(len(s30)):
    if s30[index] not in newS302:
        newS302 += s30[index]
        print(f'字符串去重Index:item:{s30[index]},newS302:{newS302}')

# 集合去重
news303 = ''
# 集合有去重的特性
setS30 = set(s30)
# 集合是无序的要转成列表后就可以拼接回来了
s30List = list(setS30)
# 用索引排序
s30List.sort(key=s30.index)
# 接收
print(f'集合去重:'+''.join(s30List))

END

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

StevenChen85

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

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

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

打赏作者

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

抵扣说明:

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

余额充值