python常见字符串处理函数与用法汇总
作者:z87276490 时间:2023-10-19 08:07:11
本文实例讲述了python常见字符串处理函数与用法。分享给大家供大家参考,具体如下:
1、find
作用:在一个较长字符串中查找子串。返回子串所在位置的最左端索引,如果没有找到则返回-1.如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,如果包含子字符串返回开始的索引值,否则返回-1。
用法:string.find()
实例:
a = ' i am a boy with no money '
print a.find('a')
输出结果:
5
print a.find('a',10,len(a))
输出结果:
-1
2、join
作用:Python中有join()和os.path.join()两个函数,具体作用如下:
1) join(): 连接字符串数组。将字符串、元组、列表中的元素以指定的字符(分隔符)连接生成一个新的字符串
2)os.path.join(): 将多个路径组合后返回
用法:
'sep'.join(seq)
sep:分隔符。可以为空
seq:要连接的元素序列、字符串、元组、字典
上面的语法即:以sep作为分隔符,将seq所有的元素合并成一个新的字符串
返回值:返回一个以分隔符sep连接各个元素后生成的字符串
实例:
seq = ['1','2','3','4','5']
sep = '+'
print sep.join(seq)
输出:
1+2+3+4+5
dirs = '','usr','bin','env'
print '/'.join(dirs)
输出:
/usr/bin/env
print os.path.join('/hello/','good/boy/','doiido')
输出:
/hello/good/boy/doiido
3、replace
作用:Python replace() 方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。
语法:str.replace(old, new[, max])
参数:
old – 将被替换的子字符串。
new – 新字符串,用于替换old子字符串。
max – 可选字符串, 替换不超过 max 次
实例:
str = "this is string example....wow!!! this is really string";
print str.replace("is", "was");
print str.replace("is", "was", 3);
输出:
thwas was string example....wow!!! thwas was really string
thwas was string example....wow!!! thwas is really string
4、split函数
描述
Python split()通过指定分隔符对字符串进行切片,如果参数num 有指定值,则仅分隔 num 个子字符串
语法
split()
方法语法:
str.split(str="", num=string.count(str)).
参数
str – 分隔符,默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等。
num – 分割次数。
返回值
返回分割后的字符串列表。
实例
以下实例展示了split()
函数的使用方法:
实例:
str = "Line1-abcdef \nLine2-abc \nLine4-abcd";
print str.split( );
print str.split(' ', 1 );
以上实例输出结果如下:
['Line1-abcdef', 'Line2-abc', 'Line4-abcd']
['Line1-abcdef', '\nLine2-abc \nLine4-abcd']
希望本文所述对大家Python程序设计有所帮助。
来源:https://blog.csdn.net/z87276490/article/details/78049358
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python实现K近邻回归,采用等权重和不等权重的方法
Python 装饰器代码解析
![](https://img.aspxhome.com/file/2023/4/79764_0s.png)
python opencv实现目标区域裁剪功能
![](https://img.aspxhome.com/file/2023/4/78524_0s.jpg)
Java使用正则表达式判断字符串是否以字符开始
MobaXterm 安装使用图文教程
![](https://img.aspxhome.com/file/2023/1/131801_0s.jpg)
SQL 语句中的通配符
plsql和tsql常用函数比对
vue proxytable代理根路径的同时增加其他代理方式
详解Python编程中对Monkey Patch猴子补丁开发方式的运用
详解win10下pytorch-gpu安装以及CUDA详细安装过程
![](https://img.aspxhome.com/file/2023/7/104857_0s.png)
numba提升python运行速度的实例方法
零基础写python爬虫之使用urllib2组件抓取网页内容
![](https://img.aspxhome.com/file/2023/1/127871_0s.png)
go语言数据结构之前缀树Trie
![](https://img.aspxhome.com/file/2023/8/97158_0s.png)
Pytorch中关于BatchNorm2d的参数解释
![](https://img.aspxhome.com/file/2023/1/128551_0s.jpg)
利用arcgis的python读取要素的X,Y方法
navicat 8 for mysql建库的方法
![](https://img.aspxhome.com/file/2023/8/112878_0s.png)
使用tensorflow框架在Colab上跑通猫狗识别代码
![](https://img.aspxhome.com/file/2023/1/104821_0s.png)
python回归分析逻辑斯蒂模型之多分类任务详解
![](https://img.aspxhome.com/file/2023/3/128603_0s.png)
对json字符串与python字符串的不同之处详解
使用Pytorch实现two-head(多输出)模型的操作
![](https://img.aspxhome.com/file/2023/2/105322_0s.png)