Python 字符串常用方法

来源:互联网 发布:淘宝图片如何搬家 编辑:程序博客网 时间:2024/05/19 21:04

1. find ()

  作用: 检查字符串中是否包含字符串str

  语法: str.find(str,beg=0,end=len(string))

参数:  str : 字符串

beg : 开始索引

end: 结束索引

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


info ='hello yangyang python 'print info.find('yangyang')print info.find('e',1)

61

str1='hello yangyang python 'str2="yangyang"print str1.find(str2)print str1.find(str2,5)print str1.find(str2,10)
结果:

66-1


2.replace ()

作用: 用新字符new替换字符串中的字符old。如果指定第三个参数max,则替换不超过 max 次。

语法:str.replace(old,new[,max] )

返回值: 返回替换之后的字符串

info="hello yangyang python"print infoprint info.replace('hello','HELLO')print info.replace('hello',"HELLO",3)
hello yangyang pythonHELLO yangyang pythonHELLO yangyang python
3. split()

通过制定分隔符对字符串进行分割,如果,参数num有指定值,仅分割Num 个字符串

语法:str.split(str=" ",num=string.count(str))

num:f分割次数

str--分隔符

返回值:返回分割后的字符串列表

info="line1-abcdf@@line2-dff@@line4-ffffff"print info.split('@@')

['line1-abcdf', 'line2-dff', 'line4-ffffff']
4. join()

作用:将序列中的元素与指定的字符串连接成一个新的字符串

语法: strjoin(string)

返回值: 新生成的字符串

str='#'str1=("a","b","c")print str.join(str1)
a#b#c
5. strip()


作用: 移除字符串头尾指定的字符(默认为空格)

方法: str.strip([chars])

chars--移除字符串头尾指定的字符

返回值: 移除头尾指定字符的新字符串

str='#hello yangyang python###'print strprint str.strip("#")

#hello yangyang python###hello yangyang python
6. format(

作用: 格式化字符串函数,通过 { }和: 代替%

format 函数可以接受不限个参数,位置可以不按顺序

print "{}{}".format("hello","world")print "{0} {1}".format("hello","world")print "{1}{0}{1}".format("hello","world")name='yyang'age=10print('hello[0],age:[1]'.format(name,age))
helloworldhello worldworldhelloworldhello[0],age:[1]





原创粉丝点击