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']
相关推荐
RadNIkMan38 分钟前
Python学习(二)操作列表
网络·python·学习
半盏茶香1 小时前
启幕数据结构算法雅航新章,穿梭C++梦幻领域的探索之旅——堆的应用之堆排、Top-K问题
java·开发语言·数据结构·c++·python·算法·链表
liuhaoran___2 小时前
解释区块链技术的应用场景和优势
python
独好紫罗兰2 小时前
洛谷题单2-P5712 【深基3.例4】Apples-python-流程图重构
开发语言·python·算法
东方佑2 小时前
深度解析Python-PPTX库:逐层解析PPT内容与实战技巧
开发语言·python·powerpoint
Python大数据分析@2 小时前
python 常用的6个爬虫第三方库
爬虫·python·php
一顿操作猛如虎,啥也不是!2 小时前
JAVA-Spring Boot多线程
开发语言·python
斯内科2 小时前
Python入门(7):Python序列结构-字典
python·字典·dictionary
云徒川2 小时前
【设计模式】过滤器模式
windows·python·设计模式