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']
相关推荐
sqyno1sky2 分钟前
Python数据库操作:SQLAlchemy ORM指南
jvm·数据库·python
belldeep13 分钟前
python:spaCy 源代码解析,性能优化方法
python·性能优化·cython·spacy
deephub24 分钟前
TPU 架构与 Pallas Kernel 编程入门:从内存层次结构到 FlashAttention
人工智能·python·深度学习·tpu
薛定谔的猫喵喵24 分钟前
卸载 Python 3.8 报错 “Could not set file security” 的终极解决方案
开发语言·python
墨尔本、晴29 分钟前
[Django-web]1.环境准备
python·django
智算菩萨1 小时前
OpenCV色彩空间转换实战:BGR转HSV/LAB的工业应用场景详解(含自动化脚本)
人工智能·python·opencv·计算机视觉·自动化·音视频
曲幽1 小时前
别再数据线了!用FastAPI 5分钟搭个局域网文件+剪贴板神器
python·fastapi·web·async·clipboard·fileupload
AbsoluteLogic1 小时前
Python——必学内置模块 OS
python
sqyno1sky1 小时前
游戏与图形界面(GUI)
jvm·数据库·python
用户8356290780511 小时前
Python 实现 Word 文档图片插入与排版技巧
后端·python