python 字符串操作大全

目录

字符串是否以xxx开头/结尾

查询操作

大小写转换

字符串对齐

字符串拆分/切割

字符串去空白(包括' ',\n,\t,\r)

字符串判断

字符串替换与合并

字符串字典序

编码与解码

精度

格式化

切片

字符串长度


字符串是否以xxx开头/结尾

s = '牛啊牛啊'
#是否开头
print(s.startswith('牛'))  # True
#是否结尾
print(s.endswith('啊'))  # True

查询操作

"""
index()查找子串substr第一次出现的位置,如果查找的子串不存在时,则抛出 ValueError 
reindex()查找子串substr最后一次出现的位置,如果查找的子串不存在时,则抛出ValueError 
find()查找子串substr第一次出现的位置,如果查找的子串不存在时,则返回-1
rfind()查找子串substr最后一次出现的位置,如果查找的子串不存在时,则返回-1
"""
str = 'helloWorLd,hello'
print(str.index('el'), str.rindex('el'), str.find('el'), str.rfind('el'),
      str.find('la'))

#1 12 1 12 -1

大小写转换

"""
upper()把字符串中所有字符都转成大写字母
lower()把字符串中所有字符都转成小写字母
swapcase()把字符串中所有大写字母转成小写字母,把所有小写字母都转成大写字母
capita1ize()把第一个字符转换为大写,把其余字符转换为小写
title()把每个单词的第一个字符转换为大写,把每个单词的剩余字符转换为小写
"""
str = 'helloWorLd,hello'
print(str)
print(str.upper())
print(str.lower())
print(str.swapcase())
print(str.capitalize())
print(str.title())

# helloWorLd,hello
# HELLOWORLD,HELLO
# helloworld,hello
# HELLOwORlD,HELLO
# Helloworld,hello
# Helloworld,Hello

字符串对齐

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

# **helloWorLd,hello**
# helloWorLd,hello****
# ****helloWorLd,hello
# 0000helloWorLd,hello

字符串拆分/切割

"""
split():
从字符串的左边开始劈分,默认的劈分字符是空格字符串,返回的值都是一个列表,
以通过参数sep指定劈分字符串是的劈分符,通过参数maxsplit指定劈分字符串时的最大劈分次数,在经过最大次劈分之后,剩余的子串会单独做为一部分
rsplit():
从字符串的右边开始劈分,默认的劈分字符是空格字符串,返回的值都是一个列表
以通过参数sep指定劈分字符串是的劈分符,通过参数maxsplit指定劈分字符串时的最大劈分次数,在经过最大次劈分之后,剩余的子串会单独做为一部分
"""
str = 'hello,world,come,on'
print(str.split(','))
print(str.split(',', 2))
print(str.rsplit(','))
print(str.rsplit(',', 2))

# ['hello', 'world', 'come', 'on']
# ['hello', 'world', 'come,on']
# ['hello', 'world', 'come', 'on']
# ['hello,world', 'come', 'on']

字符串去空白(包括' ',\n,\t,\r)

"""
strip()、lstrip()、rstrip()⽤法详解
简单来说,三种⽅法是为了删除字符串中不同位置的指定字符。其中,strip()⽤于去除字符串的⾸尾字符,同理,lstrip()⽤于去除左边的字符,rstrip()⽤于去除右边的字符
Python中有三个去除头尾字符、空⽩符的函数,它们依次为:
strip:⽤来去除头尾字符、空⽩符(包括\n、\r、\t、' ',即:换⾏、回车、制表符、空格)
lstrip:⽤来去除开头字符、空⽩符(包括\n、\r、\t、' ',即:换⾏、回车、制表符、空格)
rstrip:⽤来去除结尾字符、空⽩符(包括\n、\r、\t、' ',即:换⾏、回车、制表符、空格)
从字⾯可以看出r=right,l=left,strip、rstrip、lstrip是开发中常⽤的字符串格式化的⽅法。
注意:这些函数都只会删除头和尾的字符,中间的不会删除
"""
str = ' python '
print(str)
print(str.strip(' '))
print(str.lstrip(' '))
print(str.rstrip(' '))

#  python 
# python
# python 
#  python

字符串判断

# isidentifier()判断指定的字符串是不是合法的变量名  合法标识符只包含字母数字下划线,且不能以数字开头
print("class".isidentifier())  # True
print("_a".isidentifier())  # True
print("中国123a".isidentifier())  # True
print("123".isidentifier())  # False
print("3a".isidentifier())  # False
print("".isidentifier())  # False
# isspace()判断指定的字符串是否全部由空白字符组成(回车、换行,水平制表符)
print('      '.isspace())  # True
# isalpha()判断指定的字符串是否全部由字母组成
print('dasd132'.isalpha())  # False
print('aaasds'.isalpha())  # True
# isdecima()判断指定字符串是否全部由十进制的数字组成
print("this2009".isdecimal())  # False
print("23443434".isdecimal())  # True
# isnumeric()判断指定的字符串是否全部由数字组成,大写数字,罗马数字都返回true
print("this2009".isnumeric())  # False
print("23443434".isnumeric())  # True
# isalnum()判断指定字符串是否全部由字母和数字组成
print("this2009".isalnum())  # True
print("23443434!".isalnum())  # False

字符串替换与合并

"""
replace()第1个参数指定被替换的子串,第2
个参数指定替换子串的字符串,该方法返回替换后得到的字符串,替换前的字符串不发生变化,调用该方法时可以通过第3个参数指定最大替换次数
join()将列表或元组中的字符串合并成一个字符串
"""
str = 'hello,hello,world'
reStr1 = str.replace('hello', 'hi')
reStr2 = str.replace('hello', 'hi', 1)  # 最后的参数1表示只替换一次
print(reStr1, reStr2)

lst = ['C++', 'Python', 'Java']
print('|'.join(lst))
print(' '.join(lst))


# hi,hi,world hi,hello,world
# C++|Python|Java
# C++ Python Java

字符串字典序

print(ord('a') , ord('b'))
#97 98

编码与解码

s = '牛啊牛啊'
# 编码
gbk = s.encode(encoding='GBK')
utf = s.encode(encoding='UTF-8')
print(gbk)  # 在GBK这种编码格中一个中文占两个字节
print(utf)  # 在UTF-8这种编码格中一个中文占三个字节
# 解码
print(gbk.decode(encoding='GBK'))
print(utf.decode(encoding='UTF-8'))

# b'\xc5\xa3\xb0\xa1\xc5\xa3\xb0\xa1'
# b'\xe7\x89\x9b\xe5\x95\x8a\xe7\x89\x9b\xe5\x95\x8a'
# 牛啊牛啊
# 牛啊牛啊

精度

# 方法一
print('%5d' % 3)
print('%.3f' % 3.1415926)
print('%5.3f' % 3.1415926)
# 方法二
print('{0}'.format(3.1415926))
print('{0:.3}'.format(3.1415926))  # 3标识3个有效数字
print('{:.3f}'.format(3.1415926))  # 保留三位小数

#     3
# 3.142
# 3.142
# 3.1415926
# 3.14
# 3.142

格式化

name = 'Python'
day = 36500
# 方法一
print('我学%s已经%d天了' % (name, day))
# 方法二
print('我的名字是{0},我学习{1}天了'.format(name, day))
# 方法三
print(f'我学{name}已经{day}天了')

# 我学Python已经36500天了
# 我的名字是Python,我学习36500天了
# 我学Python已经36500天了

切片

str = 'hello,hello,world' 
s1 = str[3:10:2] #起始位置(闭),结束位置(开),步长
s2 = str[:] #复制字符串
print(s1, s2)
# l,el hello,hello,world

字符串长度

str = 'hello,hello,world'
print(len(str))

#17

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

阿尔兹

如果觉得有用就推荐给你的朋友吧

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

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

打赏作者

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

抵扣说明:

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

余额充值