首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python:字符串函数

Python:字符串函数

作者头像
py3study
发布2020-01-08 16:41:25
4060
发布2020-01-08 16:41:25
举报
文章被收录于专栏:python3python3

String模块中的常量:

string.digits:数字0~9 string.letters:所有字母(大小写) string.lowercase:所有小写字母 string.printable:可打印字符的字符串 string.punctuation:所有标点 string.uppercase:所有大写字母 >>> import string >>> string.digits '0123456789' >>> string.letters 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' >>> string.lowercase 'abcdefghijklmnopqrstuvwxyz' >>> string.printable '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c' >>> string.punctuation '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' >>> string.uppercase 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 1、find函数

在一个较长的字符串中查询子字符串,返回子串所在位置最左端索引,没有找到返回-1 >>> title = "Monty Python's Flying Circus" >>> title.find('Monty') 0 >>> title.find('monty') -1 可以选择起始点和结束点 >>> title.find('Python') 6 >>> title.find('Python', 3) 6 >>> title.find('Python', 3, 10) -1 2、join函数

在队列中添加元素(只能操作于字符串,返回一个修改后的字符串,但是原字符串不改变) >>> seq = ['1', '2', '3', '4', '5'] >>> sep = '+' >>> sep.join(seq) '1+2+3+4+5' >>> seq ['1', '2', '3', '4', '5'] >>> dirs = '', 'usr', 'bin', 'env' >>> '/'.join(dirs) '/usr/bin/env' >>> print 'C:' + '\\'.join(dirs) C:\usr\bin\env 逆方法:split函数 将字符串分割成序列,返回该序列,原字符串不改变 >>> word = '1+2+3+4+5' >>> word.split('+') ['1', '2', '3', '4', '5'] >>> word '1+2+3+4+5'

3、lower函数

返回字符串的小写字母版

>>> 'fafDAWdfaweDWED'.lower() 'fafdawdfawedwed' 扩展: title函数:首字母大写,其他小写 >>> "that's all folks".title() "That'S All Folks" capwords函数:功能同上,为string模块中函数 >>> import string >>> string.capwords("that's all folks") "That's All Folks" 4、replace函数

返回某字符串所有匹配项均被替换之后得到的字符串,原字符串不改变 >>> word = 'this is a test' >>> word.replace('is', 'eez') 'theez eez a test' >>> word 'this is a test' maketrans函数:功能同上,string中的转换表,共有256个项目,函数接受2个等长的字符串,第一个字符串中的每个字符都用第二个字符串中相应位置的字符来进行替换 maketrans类似于一种规则,经常与translate结合,以完成一些普通函数无法完成的字符串替换 >>> from string import maketrans >>> table = maketrans('cs', 'kz') >>> len(table) 256 >>> table[97:123] 'abkdefghijklmnopqrztuvwxyz' >>> maketrans('','')[97:123] 'abcdefghijklmnopqrstuvwxyz' translate函数:功能同上,但是只能处理单个字符,有2个参数,第一个是替换,第二个是删除 例:table承继maketrans中的table >>> 'this is an incredible test'.translate(table) 'thiz iz an inkredible tezt' >>> 'this is an incredible test'.translate(table, ' ') 'thizizaninkredibletezt' 5、strip函数

去除两侧(不包括内部)空格的字符串,原序列不变 >>> word = ' this is test ' >>> word.strip() 'this is test' >>> word ' this is test ' 可在strip()加入参数,以去除想要去掉的指定字符 >>> '*** SPAM * for * everyone!!! ***'.strip('*') ' SPAM * for * everyone!!! ' >>> '*** SPAM * for * everyone!!! ***'.strip('* ') 'SPAM * for * everyone!!!' >>> '*** SPAM * for * everyone!!! ***'.strip('* !') 'SPAM * for * everyone'

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-09-02 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档