Python字符串方法:字符串查找、替换、分割

字符串查找

Python 提供了内置的字符串查找方法find(),利用该方法可以在一个较长的字符串中查找子字符串。如果该字符串中,有一个或者多个子字符串,则该方法返回第一个子串所在位置的最左端索引,若没有找到符合条件的子串,则返回-1。find()方法的基本使用语法如下:

python 复制代码
source_string.find(sub_string)

其中:

  • source_string:源字符串;
  • sub_string:待查的目标子字符串;
  • find:字符串查找方法的语法关键字。

例如,在一个字符串中,查找两个单词的位置:

python 复制代码
# coding=utf-8
# 创建一个字符串
source_string = 'The past is gone and static'
# 查看"past"在source_string字符串中的位置
print(source_string.find('past'))
# 查看"love"在source_string字符串中的位置
print(source_string.find('love'))

#输出结果:
4
-1

字符串替换

Python 提供了replace()方法,用以替换给定字符串中的子串。其基本使用语法如下:

python 复制代码
source_string.replace(old_string, new_string)

其中:

  • source_string:待处理的源字符串;
  • old_string:被替换的旧字符串;
  • new_string:替换的新字符串;
  • replace:字符串替换方法的语法关键词。

例如,在如下字符串中,用small子串替换big子串:

python 复制代码
# coding = utf-8
# 创建一个字符串circle
source_string = 'The world is big'
# 利用replace()方法用子串"small"代替子串"big"
print(source_string.replace('big','small'))

#输出结果:
The world is small

字符串分割

Python 提供了split()方法实现字符串分割。该方法根据提供的分隔符,将一个字符串分割为字符列表,如果不提供分隔符,则程序会默认把空格(制表、换行等)作为分隔符。其基本使用语法如下:

python 复制代码
source_string.split(separator)

其中:

  • source_string:待处理的源字符串;
  • separator:分隔符;
  • split:字符串分割方法的关键词

例如,用+、/还有空格作为分隔符,分割字符串:

python 复制代码
# coding = utf-8
# 待处理字符串source_string
source_string = '1+2+3+4+5'
# 利用split()方法,按照`+`和`/`对source_string字符串进行分割
print(source_string.split('+'))
print(source_string.split('/'))


#输出结果:
['1', '2', '3', '4', '5']
['1+2+3+4+5']
相关推荐
乔巴先生241 小时前
LLMCompiler:基于LangGraph的并行化Agent架构高效实现
人工智能·python·langchain·人机交互
张子夜 iiii2 小时前
实战项目-----Python+OpenCV 实现对视频的椒盐噪声注入与实时平滑还原”
开发语言·python·opencv·计算机视觉
困鲲鲲3 小时前
Flask 核心基础:从 路由装饰器 到 __name__ 变量 的底层逻辑解析
python·flask
njxiejing4 小时前
Python NumPy安装、导入与入门
开发语言·python·numpy
Rhys..4 小时前
Python&Flask 使用 DBUtils 创建通用连接池
开发语言·python·mysql
Just_Paranoid4 小时前
【Python Tkinter】图形用户界面(GUI)开发及打包EXE指南
python·gui·tkinter·pyinstaller
小宁爱Python4 小时前
Django 基础入门:命令、结构与核心配置全解析
后端·python·django
闲人编程5 小时前
Flask 前后端分离架构实现支付宝电脑网站支付功能
python·架构·flask·支付宝·前后端·网站支付·apl
996终结者5 小时前
同类软件对比(四):Jupyter vs PyCharm vs VS Code:Python开发工具终极选择指南
vscode·python·jupyter·pycharm·visual studio code
果壳~5 小时前
【Python】爬虫html提取内容基础,bs4
爬虫·python·html