python用的比较多的字符串处理函数

来源:互联网 发布:圣兰软件 编辑:程序博客网 时间:2024/06/05 20:23

返回sub在字符串str中出现的次数

str.count(sub, start= 0,end=len(string))
  • sub – 搜索的子字符串
  • start – 字符串开始搜索的位置。默认为第一个字符,第一个字符索引值为0。
  • end – 字符串中结束搜索的位置。字符中第一个字符的索引为 0。默认为字符串的最后一个位置。

如果包含子字符串返回开始的索引值,否则返回-1

str.find(str, beg=0, end=len(string))
  • str – 指定检索的字符串
  • beg – 开始索引,默认为0。
  • end – 结束索引,默认为字符串的长度。

格式化字符串,返回一个新字符串

Python2.6 开始,新增了一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能。
基本语法是通过 {} 和 : 来代替以前的 % 。
format 函数可以接受不限个参数,位置可以不按顺序。

#!/usr/bin/python# -*- coding: UTF-8 -*-print("网站名:{name}, 地址 {url}".format(name="菜鸟教程", url="www.runoob.com"))# 通过字典设置参数site = {"name": "菜鸟教程", "url": "www.runoob.com"}print("网站名:{name}, 地址 {url}".format(**site))# 通过列表索引设置参数my_list = ['菜鸟教程', 'www.runoob.com']print("网站名:{0[0]}, 地址 {0[1]}".format(my_list))  # "0" 是必须的

返回通过指定字符连接序列中元素后生成的新字符串

str.join(sequence)
  • sequence – 要连接的元素序列。

实例:

#!/usr/bin/pythonstr = "-";seq = ("a", "b", "c"); # 字符串序列print str.join( seq );

输出:
a-b-c


返回一个3元的元组,第一个为分隔符左边的子串,第二个为分隔符本身,第三个为分隔符右边的子串

直接看实例:

#!/usr/bin/pythonstr = "http://www.w3cschool.cc/"print str.partition("://")

输出结果:

('http', '://', 'www.w3cschool.cc/') #返回一个元组

返回被替换的新字符串

直接看实例:

#!/usr/bin/pythonstr = "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 stringthwas was string example....wow!!! thwas is really string

返回分割后的字符串列表

直接看实例: ps:与JS中的split是一模一样的

#!/usr/bin/pythonstr = "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']

再加一个实例:

#!/usr/bin/python# -*- coding: UTF-8 -*-import rea='Beautiful, is; better*than\nugly'# 四个分隔符为:,  ;  *  \nx= re.split(',|; |\*|\n',a)print(x)

输出结果:['Beautiful', ' is', 'better', 'than', 'ugly']


返回移除字符串头尾指定的字符生成的新字符串

Python strip() 方法用于移除字符串头尾指定的字符(默认为空格)。
实例:

#!/usr/bin/pythonstr = "0000000this is string example....wow!!!0000000";print str.strip( '0' );

输出结果:this is string example....wow!!!


返回翻译后的字符串

ps:特定字符对应特定字符一对一替换
实例:

#!/usr/bin/pythonfrom string import maketrans   # 引用 maketrans 函数。intab = "aeiou" # 原字符串中如果有这些字符outtab = "12345" # 就会被翻译成这些字符替代trantab = maketrans(intab, outtab)str = "this is string example....wow!!!";print str.translate(trantab);

输出结果:th3s 3s str3ng 2x1mpl2....w4w!!!
可见原字符串中的 i e a o 被换成了数字的 3 2 1 4

原创粉丝点击