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']
相关推荐
tjjucheng4 小时前
靠谱的小程序定制开发哪个好
python
num_killer5 小时前
小白的Langchain学习
java·python·学习·langchain
WangYaolove13145 小时前
基于深度学习的中文情感分析系统(源码+文档)
python·深度学习·django·毕业设计·源码
自学不成才6 小时前
深度复盘:一次flutter应用基于内存取证的黑盒加密破解实录并完善算法推理助手
c++·python·算法·数据挖掘
徐先生 @_@|||6 小时前
Palantir Foundry 五层架构模型详解
开发语言·python·深度学习·算法·机器学习·架构
深蓝电商API7 小时前
Scrapy爬虫限速与并发控制最佳实践
爬虫·python·scrapy
Derrick__17 小时前
淘宝MD5爬虫
爬虫·python
薛定谔的猫19827 小时前
llama-index Embedding 落地到 RAG 系统
开发语言·人工智能·python·llama-index
nimadan129 小时前
**手机小说扫榜工具2025推荐,精准追踪榜单动态与题材风向
python·智能手机
编程武士9 小时前
Python 各版本主要变化速览
开发语言·python