教程集 www.jiaochengji.com
教程集 >  Python编程  >  Python入门  >  正文 Python字符串操查找替换分割和连接方的法及使用

Python字符串操查找替换分割和连接方的法及使用

发布时间:2021-12-26   编辑:jiaochengji.com
教程集为您提供Python字符串操查找替换分割和连接方的法及使用等资源,欢迎您收藏本站,我们将为您提供最新的Python字符串操查找替换分割和连接方的法及使用资源

str提供了如下常用的执行查找、替换等操作的方法:

startswith():判断字符串是否以指定子串开头。

endswith():判断字符串是否以指定子串结尾。

find():查找指定子串在字符串中出现的位置,如果没有找到指定子串,则返回 -1。

index():查找指定子串在字符串中出现的位置,如果没有找到指定子串,则引发 ValueError 错误。

replace():使用指定子串替换字符串中的目标子串。

translate():使用指定的翻译映射表对字符串执行替换。

如下代码示范了上面方法的用法:

<pre class="brush:html;toolbar:false">s = 'crazyit.org is a good site' # 判断s是否以crazyit开头 print(s.startswith('crazyit')) # 判断s是否以site结尾 print(s.endswith('site')) # 查找s中'org'的出现位置 print(s.find('org')) # 8 # 查找s中'org'的出现位置 print(s.index('org')) # 8 # 从索引为9处开始查找'org'的出现位置 #print(s.find('org', 9)) # -1 # 从索引为9处开始查找'org'的出现位置 print(s.index('org', 9)) # 引发错误 # 将字符串中所有it替换成xxxx print(s.replace('it', 'xxxx')) # 将字符串中1个it替换成xxxx print(s.replace('it', 'xxxx', 1)) # 定义替换表:97(a)->945(α),98(b)->945(β),116(t)->964(τ), table = {97: 945, 98: 946, 116: 964} print(s.translate(table)) # crαzyiτ.org is α good siτe</pre>

Python字符串分割、连接方法

Python 还为 str 提供了分割和连接方法:

split():将字符串按指定分割符分割成多个短语。

join():将多个短语连接成字符串。

下面代码示范了上面两个方法的用法:

<pre class="brush:html;toolbar:false">s = 'crazyit.org is a good site' # 使用空白对字符串进行分割 print(s.split()) # 输出 ['crazyit.org', 'is', 'a', 'good', 'site'] # 使用空白对字符串进行分割,最多只分割前2个单词 print(s.split(None, 2)) # 输出 ['crazyit.org', 'is', 'a good site'] # 使用点进行分割 print(s.split('.')) # 输出 ['crazyit', 'org is a good site'] mylist = s.split() # 使用'/'为分割符,将mylist连接成字符串 print('/'.join(mylist)) # 输出 crazyit.org/is/a/good/site # 使用','为分割符,将mylist连接成字符串 print(','.join(mylist)) # 输出 crazyit.org,is,a,good,site</pre>

您可能感兴趣的文章:
Python字符串操查找替换分割和连接方的法及使用
python string是什么
php5 字符串处理函数汇总
php字符串操作函数入门篇
Python之字符串中常用的方法
Python split()方法详解:分割字符串
PHP中字符串处理的一些常用函数
伸手党必备之Python正则表达式常用函数
PHP中常用的18个字符串函数
php array数组的相关处理函数and str字符串处理与正则表达式

[关闭]
~ ~