当前位置: 首页 > news >正文

Python3.x String内置函数大全

文章目录

  • 总结一下Python3.x字符串的常用系统函数,总共分为8类
    • 1. 大小写字母转换类的函数
      • str.capitalize()
      • str.title()
      • str.lower()
      • str.upper()
      • str.swapcase()
    • 2. 统计类的函数
      • str.count(str1, beg= 0,end=len(string))
    • 3. 匹配类的函数
      • str.endswith(suffix, beg=0, end=len(string))
      • str.startswith(substr, beg=0,end=len(string))
      • str.isnumeric()
      • str.isdigit()
      • str.isalpha()
      • str.isa1num()
      • str.find(str1, beg=0, end=len(string))
      • str.rfind(str1, beg=0,end=len(string))
      • str.index(str1, beg=0, end=len(string))
      • str.replace(old, new [, max])
    • 4. 格式化类的函数
      • str.ljust(width[, fillchar])
      • str.rjust(width[, fillchar])
      • str.center(width[, fillchar])
    • 5. 移除类的函数
      • str.lstrip([chars])
      • str.rstrip([chars])
      • str.strip([chars])
    • 6. 分割类函数
      • str.partition(sep)
      • str.rpartition(sub)
      • str.split(sep=None, maxsplit=-1)
      • str.splitlines([keepends=False])
    • 7. 合并类的函数
      • str.join(iterable)
    • 8. 映射类函数
      • str.maketrans(intab, outtab)
      • str.translate(table, deletechars="")

总结一下Python3.x字符串的常用系统函数,总共分为8类

1. 大小写字母转换类的函数

str.capitalize()

:将字符串的第一个字符转换为大写。

【例子】

print(s.capitalize())  # Xiao xie

str.title()

:方法返回"标题化"的字符串,就是说所有单词都是以大写开始,其余字母均为小写。

【例子】

print(s.title())  # Xiao Xie

str.lower()

:转换字符串中所有大写字符为小写。

【例子】

print(s.lower())  # daxiexiaoxie

str.upper()

:转换字符串中的小写字母为大写。

【例子】

print(s.upper())  # DAXIEXIAOXIE

str.swapcase()

:将字符串中大写转换为小写,小写转换为大写。

【例子】

print(s.swapcase())  # daxieXIAOXIE

2. 统计类的函数

str.count(str1, beg= 0,end=len(string))

:返回 str1 在 string 里面出现的次数,如果 beg 或者 end 指定则返回指定范围内 str1 出现的次数。

【例子】

print(s.count('xi'))  # 2
print(s.count('XI')) # 1

3. 匹配类的函数

str.endswith(suffix, beg=0, end=len(string))

:检查字符串是否以指定子字符串suffix 结束,如果是,返回 True ,否则返回 False 。如果 beg 和 end 指定值,则在指定范围内检查。

【例子】

print(s.endswith('ie'))  # True
print(s.endswith('xi'))  # False

str.startswith(substr, beg=0,end=len(string))

:检查字符串是否以指定子字符串 substr 开头,如果是,返回 True ,否则返回 False 。如果 beg 和 end 指定值,则在指定范围内检查。

【例子】

print(s.startswith('Da'))  # False
print(s.startswith('DA'))  # True

str.isnumeric()

:检测字符串是否只由数字组成,这种方法是只针对unicode对象。如果字符串中只包含数字字符,则返回 True ,否则返回 False 。注意: 在Python2中,普通字符串是以8位ASCII码进行存储的,而Unicode字符串则存储为16位unicode字符串, 这样能够表示更多的字符集。使用的语法是在字符串前面加上前缀 u。 在Python3中,所有的字符串都是Unicode字符串。

【例子】

print(s.isnumeric())  # True
s += 'a'
print(s.isnumeric())  # False

str.isdigit()

:检测字符串是否只由数字组成,如果字符串只包含数字,则返回 True 否则返回 False 。

【例子】

print(s.isdigit())  # True
s += 'a'
print(s.isdigit())  # False

str.isalpha()

:检测字符串是否只由字母组成。如果字符串至少有一个字符并且所有字符都是字母则返回 True ,否则返回 False 。

【例子】

print(s.isalpha())  # True
s = ' I Love LsgoGroup '
print(s.isalpha())  # False

str.isa1num()

:检测字符串是否由字母和数字组成。如果 string 至少有一个字符并且所有字符都是字母或数字则返回 True ,否则返回 False 。

【例子】

print(s.isalnum())  # True
s = ' I Love LsgoGroup '
print(s.isalnum())  # False

str.find(str1, beg=0, end=len(string))

:检测 str1 是否包含在字符串中,如果指定范围 beg 和 end ,则检查是否包含在指定范围内,如果包含,返回开始的索引值,否则返回 -1。

【例子】

print(s.find('xi'))  # 5
print(s.find('ix'))  # -1

str.rfind(str1, beg=0,end=len(string))

:类似于 find() 函数,不过是从右边开始查找。

【例子】

print(s.rfind('xi'))  # 9

str.index(str1, beg=0, end=len(string))

:检测字符串中是否包含子字符串 str1 ,如果指定 beg (开始) 和 end (结束) 范围,则检查是否包含在指定范围内,该方法与 find() 方法一样,只不过如果 str1 不在 string中会报一个异常。

【例子】

print(s.index('xi'))  # 5
print(s.index('ix'))  # ValueError: substring not found

str.replace(old, new [, max])

:将字符串中的 old 替换成 new ,如果 max 指定,则替换不超过 max 次。

【例子】

print(s.replace('I', 'We'))  # ' We Love LsgoGroup '

4. 格式化类的函数

str.ljust(width[, fillchar])

:返回一个原字符串左对齐,并使用 fillchar
(默认空格)填充至长度 width 的新字符串。

【例子】

print(s.ljust(8, '0'))  # 11010000

str.rjust(width[, fillchar])

:返回一个原字符串右对齐,并使用 fillchar (默认空格)填充至长度 width 的新字符串。

【例子】

print(s.rjust(8, '0'))  # 00001101

str.center(width[, fillchar])

:返回一个指定的宽度 width 居中的字符串, fillchar 为填充的字符,默认为空格。

【例子】

print(s.center(8, '0'))  # 00110100

5. 移除类的函数

str.lstrip([chars])

:截掉字符串左边的空格或指定字符。

【例子】

print(s.lstrip())  # 'I Love LsgoGroup '
print(s.lstrip().lstrip('I'))  # ' Love LsgoGroup '

str.rstrip([chars])

:删除字符串末尾的空格或指定字符。

【例子】

print(s.rstrip())  # ' I Love LsgoGroup'
print(s.rstrip().rstrip('up')) # ' I Love LsgoGro'

str.strip([chars])

:在字符串上执行 lstrip() 和 rstrip() 。

【例子】

print(s.strip())  # 'I Love LsgoGroup'
print(s.strip().strip('p'))  # 'I Love LsgoGrou'

6. 分割类函数

str.partition(sep)

:找到子字符串 sep ,把字符串分为一个三元组 (pre_sep,sep,fol_sep) ,如果字符串中不包含 sep 则返回 ('原字符串','','') 。

【例子】

print(s.strip().partition('o'))  # ('I L', 'o', 've LsgoGroup')
print(s.strip().partition('m'))  # ('I Love LsgoGroup', '', '')

str.rpartition(sub)

:类似于 partition() 方法,不过是从右边开始查找。

【例子】

print(s.strip().rpartition('o'))  # ('I Love LsgoGr', 'o', 'up')
print(s.strip().rpartition('m')) # ('', '', 'I Love LsgoGroup')

str.split(sep=None, maxsplit=-1)

:不带参数默认是以空格为分隔符切片字符串,如果 maxsplit 参数有设置,则仅分隔 maxsplit 个子字符串,返回切片后的子字符串拼接的列表。

【例子】

print(s.strip().split())  # ['I', 'Love', 'LsgoGroup']
print(s.strip().split('o'))  # ['I L', 've Lsg', 'Gr', 'up']

【例子】

 使用默认分隔符
print(u.split())  # ['www.baidu.com.cn']以"."为分隔符
print(u.split('.'))  # ['www', 'baidu', 'com', 'cn']分割0次
print(u.split(".", 0))  # ['www.baidu.com.cn']分割一次
print(u.split(".", 1))  # ['www', 'baidu.com.cn']分割两次
print(u.split(".", 2))  # ['www', 'baidu', 'com.cn']分割两次,并取序列为1的项
print((u.split(".", 2)[1]))  # baidu分割两次,并把分割后的三个部分保存到三个变量
u1, u2, u3 = u.split(".", 2)
print(u1)  # www
print(u2)  # baidu
print(u3)  # com.cn
**【例子】**去掉换行符c = '''
say
hello
baby
'''print(c)sayhellobabyprint(c.split('\n'))  # ['', 'say', 'hello', 'baby', '']
**【例子】**s = "hello boy<[www.baidu.com]>byebye"
print(s.split('[')[1].split(']')[0])  # www.baidu.com
print(s.split('[')[1].split(']')[0].split('.'))  # ['www', 'baidu', 'com']

str.splitlines([keepends=False])

:按照行('\r', '\r\n', \n')分隔,返回一个包含各行作为元素的列表,如果参数 keepends 为 False ,不包含换行符,如果为 True ,则保留换行符。

【例子】

print(s.splitlines())  # ['I ', ' Love ', ' LsgoGroup']
print(s.splitlines(True))  # ['I \n', ' Love \n', ' LsgoGroup']

7. 合并类的函数

str.join(iterable)

:是 split()方法的逆方法,用来将列表(或元组)中包含的多个字符串连接成一个字符串。使用 join() 方法合并字符串时,它会将列表(或元组)中多个字符串采用固定的分隔符连接在一起。

【例子】 将列表中的字符串合并成一个字符串。

print('.'.join(lst))www.lsgogroup.net
字符串“www.lsgogroup.net”可以看做是通过分隔符“.”将
['www','lsgogroup','net']
列表合并为一个字符串的结果。

【例子】将元组中的字符串合并成一个字符串。

  print('\\'.join(dir))C:\Users\Public\Pictures

8. 映射类函数

str.maketrans(intab, outtab)

:创建字符映射的转换表,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标。

【例子】

intab = 'aeiou'
outtab = '12345'
trantab = s.maketrans(intab, outtab)
print(trantab)  # {97: 49, 101: 50, 105: 51, 111: 52, 117: 53}

str.translate(table, deletechars=“”)

:根据参数 table 给出的表,转换字符串的字符,要过滤掉的字符放到 deletechars 参数中。

【例子】

intab = 'aeiou'
outtab = '12345'
trantab = s.maketrans(intab, outtab)
print(s.translate(trantab))  # th3s 3s str3ng 2x1mpl2....w4w!!!```
http://www.lryc.cn/news/117996.html

相关文章:

  • Go异常处理机制panic和recover
  • QMainwindow窗口
  • P5735 【深基7.例1】距离函数
  • prometheus告警发送组件部署
  • CAPL - XML和TestModule结合实现测试项可选
  • Latex安装与环境配置(TeXlive、TeXstudio与VS code的安装)编译器+编辑器与学习应用
  • STM32 F103C8T6学习笔记3:串口配置—串口收发—自定义Printf函数
  • python中字符串内建函数篇4
  • 并发下如何使用redis存储列表数据
  • Leecode螺旋矩阵 II59
  • echarts 横向柱状图
  • Vue3 —— to 全家桶及源码学习
  • (第三篇) ansible-kubeadm在线安装高可以用集群()
  • flutter开发实战-颜色Color与16进制转换
  • Linux(进程地址空间)
  • VLAN监控及常见问题排查
  • PromQL实现Actuator获取的JVM指标的Full GC次数监控
  • 3.正则表达式
  • 【学习FreeRTOS】第3章——FreeRTOS移植及配置文件
  • Java算法_ LRU 缓存(LeetCode_Hot100)
  • Hugging Face 的文本生成和大语言模型的开源生态
  • Docker Compose用法详解
  • 分布式链路追踪概述
  • css中的var函数
  • 第五次作业 运维高级 构建 LVS-DR 集群和配置nginx负载均衡
  • neo4j电影库-关系查询
  • 2020/10-2023/7 Notes
  • 在UOS系统中管理ORACLE数据库
  • 以http_proxy和ajp_proxy方式整合apache和tomcat(动静分离)
  • 【pinia】Pinia入门和基本使用: