31个必备的python字符串方法,建议收藏
off999 2025-04-24 07:14 25 浏览 0 评论
字符串是Python中基本的数据类型,几乎在每个Python程序中都会使用到它。
1、Slicing
slicing切片,按照一定条件从列表或者元组中取出部分元素(比如特定范围、索引、分割值)
s = ' hello '
s = s[:]
print(s)
# hello
s = ' hello '
s = s[3:8]
print(s)
# hello
2、strip()
strip()方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。
s = ' hello '.strip()
print(s)
# hello
s = '###hello###'.strip()
print(s)
# ###hello###
在使用strip()方法时,默认去除空格或换行符,所以#号并没有去除。
可以给strip()方法添加指定字符,如下所示。
s = '###hello###'.strip('#')
print(s)
# hello
此外当指定内容不在头尾处时,并不会被去除。
s = ' \n \t hello\n'.strip('\n')
print(s)
#
# hello
s = '\n \t hello\n'.strip('\n')
print(s)
# hello
第一个\n前有个空格,所以只会去取尾部的换行符。
最后strip()方法的参数是剥离其值的所有组合,这个可以看下面这个案例。
s = 'www.baidu.com'.strip('cmow.')
print(s)
# baidu
最外层的首字符和尾字符参数值将从字符串中剥离。字符从前端移除,直到到达一个不包含在字符集中的字符串字符为止。
在尾部也会发生类似的动作。
3、lstrip()
移除字符串左侧指定的字符(默认为空格或换行符)或字符序列。
s = ' hello '.lstrip()
print(s)
# hello
同样的,可以移除左侧所有包含在字符集中的字符串。
s = 'Arthur: three!'.lstrip('Arthur: ')
print(s)
# ee!
4、rstrip()
移除字符串右侧指定的字符(默认为空格或换行符)或字符序列。
s = ' hello '.rstrip()
print(s)
# hello
5、removeprefix()
Python3.9中移除前缀的函数。
# python 3.9
s = 'Arthur: three!'.removeprefix('Arthur: ')
print(s)
# three!
和strip()相比,并不会把字符集中的字符串进行逐个匹配。
6、removesuffix()
Python3.9中移除后缀的函数。
s = 'HelloPython'.removesuffix('Python')
print(s)
# Hello
7、replace()
把字符串中的内容替换成指定的内容。
s = 'string methods in python'.replace(' ', '-')
print(s)
# string-methods-in-python
s = 'string methods in python'.replace(' ', '')
print(s)
# stringmethodsinpython
8、re.sub()
re是正则的表达式,sub是substitute表示替换。
re.sub则是相对复杂点的替换。
import re
s = "string methods in python"
s2 = s.replace(' ', '-')
print(s2)
# string----methods-in-python
s = "string methods in python"
s2 = re.sub("\s+", "-", s)
print(s2)
# string-methods-in-python
和replace()做对比,使用re.sub()进行替换操作,确实更高级点。
9、split()
对字符串做分隔处理,最终的结果是一个列表。
s = 'string methods in python'.split()
print(s)
# ['string', 'methods', 'in', 'python']
当不指定分隔符时,默认按空格分隔。
s = 'string methods in python'.split(',')
print(s)
# ['string methods in python']
此外,还可以指定字符串的分隔次数。
s = 'string methods in python'.split(' ', maxsplit=1)
print(s)
# ['string', 'methods in python']
10、rsplit()
从右侧开始对字符串进行分隔。
s = 'string methods in python'.rsplit(' ', maxsplit=1)
print(s)
# ['string methods in', 'python']
11、join()
string.join(seq)。以string作为分隔符,将seq中所有的元素(的字符串表示)合并为一个新的字符串。
list_of_strings = ['string', 'methods', 'in', 'python']
s = '-'.join(list_of_strings)
print(s)
# string-methods-in-python
list_of_strings = ['string', 'methods', 'in', 'python']
s = ' '.join(list_of_strings)
print(s)
# string methods in python
12、upper()
将字符串中的字母,全部转换为大写。
s = 'simple is better than complex'.upper()
print(s)
# SIMPLE IS BETTER THAN COMPLEX
13、lower()
将字符串中的字母,全部转换为小写。
s = 'SIMPLE IS BETTER THAN COMPLEX'.lower()
print(s)
# simple is better than complex
14、capitalize()
将字符串中的首个字母转换为大写。
s = 'simple is better than complex'.capitalize()
print(s)
# Simple is better than complex
15、islower()
判断字符串中的所有字母是否都为小写,是则返回True,否则返回False。
print('SIMPLE IS BETTER THAN COMPLEX'.islower()) # False
print('simple is better than complex'.islower()) # True
16、isupper()
判断字符串中的所有字母是否都为大写,是则返回True,否则返回False。
print('SIMPLE IS BETTER THAN COMPLEX'.isupper()) # True
print('SIMPLE IS BETTER THAN complex'.isupper()) # False
17、isalpha()
如果字符串至少有一个字符并且所有字符都是字母,则返回 True,否则返回 False。
s = 'python'
print(s.isalpha())
# True
s = '123'
print(s.isalpha())
# False
s = 'python123'
print(s.isalpha())
# False
s = 'python-123'
print(s.isalpha())
# False
18、isnumeric()
如果字符串中只包含数字字符,则返回 True,否则返回 False。
s = 'python'
print(s.isnumeric())
# False
s = '123'
print(s.isnumeric())
# True
s = 'python123'
print(s.isnumeric())
# False
s = 'python-123'
print(s.isnumeric())
# False
19、isalnum()
如果字符串中至少有一个字符并且所有字符都是字母或数字,则返回True,否则返回 False。
s = 'python'
print(s.isalnum())
# True
s = '123'
print(s.isalnum())
# True
s = 'python123'
print(s.isalnum())
# True
s = 'python-123'
print(s.isalnum())
# False
20、count()
返回指定内容在字符串中出现的次数。
n = 'hello world'.count('o')
print(n)
# 2
n = 'hello world'.count('oo')
print(n)
# 0
21、find()
检测指定内容是否包含在字符串中,如果是返回开始的索引值,否则返回-1。
s = 'Machine Learning'
idx = s.find('a')
print(idx)
print(s[idx:])
# 1
# achine Learning
s = 'Machine Learning'
idx = s.find('aa')
print(idx)
print(s[idx:])
# -1
# g
此外,还可以指定开始的范围。
s = 'Machine Learning'
idx = s.find('a', 2)
print(idx)
print(s[idx:])
# 10
# arning
22、rfind()
类似于find()函数,返回字符串最后一次出现的位置,如果没有匹配项则返回 -1。
s = 'Machine Learning'
idx = s.rfind('a')
print(idx)
print(s[idx:])
# 10
# arning
23、startswith()
检查字符串是否是以指定内容开头,是则返回 True,否则返回 False。
print('Patrick'.startswith('P'))
# True
24、endswith()
检查字符串是否是以指定内容结束,是则返回 True,否则返回 False。
print('Patrick'.endswith('ck'))
# True
25、partition()
string.partition(str),有点像find()和split()的结合体。
从str出现的第一个位置起,把字符串string分成一个3 元素的元组(string_pre_str,str,string_post_str),如果string中不包含str则 string_pre_str==string。
s = 'Python is awesome!'
parts = s.partition('is')
print(parts)
# ('Python ', 'is', ' awesome!')
s = 'Python is awesome!'
parts = s.partition('was')
print(parts)
# ('Python is awesome!', '', '')
26、center()
返回一个原字符串居中,并使用空格填充至长度width的新字符串。
s = 'Python is awesome!'
s = s.center(30, '-')
print(s)
# ------Python is awesome!------
27、ljust()
返回一个原字符串左对齐,并使用空格填充至长度width的新字符串。
s = 'Python is awesome!'
s = s.ljust(30, '-')
print(s)
# Python is awesome!------------
28、rjust()
返回一个原字符串右对齐,并使用空格填充至长度width的新字符串。
s = 'Python is awesome!'
s = s.rjust(30, '-')
print(s)
# ------------Python is awesome!
29、f-Strings
f-string是格式化字符串的新语法。
与其他格式化方式相比,它们不仅更易读,更简洁,不易出错,而且速度更快!
num = 1
language = 'Python'
s = f'{language} is the number {num} in programming!'
print(s)
# Python is the number 1 in programming!
num = 1
language = 'Python'
s = f'{language} is the number {num*8} in programming!'
print(s)
# Python is the number 8 in programming!
30、swapcase()
翻转字符串中的字母大小写。
s = 'HELLO world'
s = s.swapcase()
print(s)
# hello WORLD
31、zfill()
string.zfill(width)。
返回长度为width的字符串,原字符串string右对齐,前面填充0。
s = '42'.zfill(5)
print(s)
# 00042
s = '-42'.zfill(5)
print(s)
# -0042
s = '+42'.zfill(5)
print(s)
# +0042
- 上一篇:Python字符串split的六种用法
- 下一篇:Python内置函数详解
相关推荐
- 使用 python-fire 快速构建 CLI_如何搭建python项目架构
-
命令行应用程序是开发人员最好的朋友。想快速完成某事?只需敲击几下键盘,您就已经拥有了想要的东西。Python是许多开发人员在需要快速组合某些东西时选择的第一语言。但是我们拼凑起来的东西在大多数时候并...
- Python 闭包:从底层逻辑到实战避坑,附安全防护指南
-
一、闭包到底是什么?你可以把闭包理解成一个"带记忆的函数"。它诞生时会悄悄记下自己周围的变量,哪怕跑到别的地方执行,这些"记忆"也不会丢失。就像有人出门时总会带上...
- 使用Python实现九九乘法表的打印_用python打印一个九九乘法表
-
任务要求九九乘法表的结构如下:1×1=11×2=22×2=41×3=32×3=63×3=9...1×9=92×9=18...9×9=81使用Python编写程序,按照上述格式打印出完整的九...
- 吊打面试官(四)--Java语法基础运算符一文全掌握
-
简介本文介绍了Java运算符相关知识,包含运算规则,运算符使用经验,特殊运算符注意事项等,全文5400字。熟悉了这些内容,在运算符这块就可以吊打面试官了。Java运算符的规则与特性1.贪心规则(Ma...
- Python三目运算基础与进阶_python三目运算符判断三个变量
-
#头条创作挑战赛#Python中你学会了三步运算,你将会省去很多无用的代码,我接下来由基础到进阶的方式讲解Python三目运算基础在Python中,三目运算符也称为条件表达式。它可以通过一行代码实现条...
- Python 中 必须掌握的 20 个核心函数——set()详解
-
set()是Python中用于创建集合的核心函数,集合是一种无序、不重复元素的容器,非常适合用于成员检测、去重和数学集合运算。一、set()的基本用法1.1创建空集合#创建空集合empty_se...
- 15个让Python编码效率翻倍的实用技巧
-
在软件开发领域,代码质量往往比代码数量更重要。本文整理的15个Python编码技巧,源自开发者在真实项目中验证过的工作方法,能够帮助您用更简洁的代码实现更清晰的逻辑。这些技巧覆盖基础语法优化到高级特性...
- 《Python从小白到入门》自学课程目录汇总(和猫妹学Python)
-
小朋友们好,大朋友们好!不知不觉,这套猫妹自学Python基础课程已经结束了,猫妹体会到了水滴石穿的力量。水一直向下滴,时间长了能把石头滴穿。只要坚持不懈,细微之力也能做出很难办的事。就比如咱们的学习...
- 8÷2(2+2) 等于1还是16?国外网友为这道小学数学题吵疯了……
-
近日,国外网友因为一道小学数学题在推特上争得热火朝天。事情的起因是一个推特网友@pjmdoll发布了一条推文,让他的关注者解答一道数学题:Viralmathequationshavebeen...
- Python学不会来打我(21)python表达式知识点汇总
-
在Python中,表达式是由变量、运算符、函数调用等组合而成的语句,用于产生值或执行特定操作。以下是对Python中常见表达式的详细讲解:1.1算术表达式涉及数学运算的表达式。例如:a=5b...
- Python运算符:数学助手,轻松拿咧
-
Python中的运算符就像是生活中的数学助手,帮助我们快速准确地完成这些计算。比如购物时计算总价、做家务时分配任务等。这篇文章就来详细聊聊Python中的各种运算符,并通过实际代码示例帮助你更好地理解...
- Python学不会来打我(17)逻辑运算符的使用方法与使用场景
-
在Python编程中,逻辑运算符(LogicalOperators)是用于组合多个条件表达式的关键工具。它们可以将多个布尔表达式连接起来,形成更复杂的判断逻辑,并返回一个布尔值(True或Fa...
- Python编程基础:运算符的优先级_python中的运算符优先级问题
-
多个运算符同时出现在一个表达式中时,先执行哪个,后执行哪个,这就涉及运算符的优先级。如数学表达式,有+、-、×、÷、()等,优先级顺序是()、×、÷、+、-,如5+(5-3)×4÷2,先计算(5-3)...
- Python运算符与表达式_python中运算符&的功能
-
一、运算符分类总览1.Python运算符全景图2.运算符优先级表表1.3.1Python运算符优先级(从高到低)优先级运算符描述结合性1**指数右→左2~+-位非/一元加减右→左3*//...
- Python操作Excel:从基础到高级的深度实践
-
Python凭借其丰富的库生态系统,已成为自动化处理Excel数据的强大工具。本文将深入探讨五个关键领域,通过实际代码示例展示如何利用Python进行高效的Excel操作,涵盖数据处理、格式控制、可视...
你 发表评论:
欢迎- 一周热门
- 最近发表
-
- 使用 python-fire 快速构建 CLI_如何搭建python项目架构
- Python 闭包:从底层逻辑到实战避坑,附安全防护指南
- 使用Python实现九九乘法表的打印_用python打印一个九九乘法表
- 吊打面试官(四)--Java语法基础运算符一文全掌握
- Python三目运算基础与进阶_python三目运算符判断三个变量
- Python 中 必须掌握的 20 个核心函数——set()详解
- 15个让Python编码效率翻倍的实用技巧
- 《Python从小白到入门》自学课程目录汇总(和猫妹学Python)
- 8÷2(2+2) 等于1还是16?国外网友为这道小学数学题吵疯了……
- Python学不会来打我(21)python表达式知识点汇总
- 标签列表
-
- python计时 (73)
- python安装路径 (56)
- python类型转换 (93)
- python进度条 (67)
- python吧 (67)
- python的for循环 (65)
- python格式化字符串 (61)
- python静态方法 (57)
- python列表切片 (59)
- python面向对象编程 (60)
- python 代码加密 (65)
- python串口编程 (77)
- python封装 (57)
- python写入txt (66)
- python读取文件夹下所有文件 (59)
- python操作mysql数据库 (66)
- python获取列表的长度 (64)
- python接口 (63)
- python调用函数 (57)
- python多态 (60)
- python匿名函数 (59)
- python打印九九乘法表 (65)
- python赋值 (62)
- python异常 (69)
- python元祖 (57)