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']
相关推荐
YYXZZ。。20 分钟前
PyTorch——搭建小实战和Sequential的使用(7)
人工智能·pytorch·python
四川兔兔23 分钟前
pytorch 与 张量的处理
人工智能·pytorch·python
AI蜗牛之家4 小时前
Qwen系列之Qwen3解读:最强开源模型的细节拆解
人工智能·python
whyeekkk4 小时前
python打卡第48天
开发语言·python
Eiceblue7 小时前
Python读取PDF:文本、图片与文档属性
数据库·python·pdf
weixin_527550407 小时前
初级程序员入门指南
javascript·python·算法
程序员的世界你不懂7 小时前
Appium+python自动化(十)- 元素定位
python·appium·自动化
CryptoPP8 小时前
使用WebSocket实时获取印度股票数据源(无调用次数限制)实战
后端·python·websocket·网络协议·区块链
树叶@8 小时前
Python数据分析7
开发语言·python
老胖闲聊9 小时前
Python Rio 【图像处理】库简介
开发语言·图像处理·python