十分钟掌握python高效操作字符串的函数

在Python的众多函数中,能够十分方便地操作字符串的函数,小编认为就有必要提及到strip()和replace()了。

十分钟掌握python高效操作字符串的函数

strip() 方法

概念:用于移除字符串头尾指定的字符(默认为空格)。

strip()语法:str.strip([chars]);

参数:chars,即对应需要操作的字符串

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

举个例子:

代码演示:

str1 = "0000000 infonan 0000000"
print(str1.strip( '0' )) # 去除首尾字符 0 
 
str2 = " infonan " # 去除首尾空格
print(str2.strip())

输出结果:

infonan

infonan

trip()函数的其他用法:

  • str.strip(str_rm) 删除str字符串中开头、结尾处,位于str_rm删除序列的字符
  • str.lstrip(str_rm) 删除str字符串中开头处,位于str_rm删除序列的字符
  • str.rstrip(str_rm) 删除str字符串中结尾处,位于str_rm删除序列的字符

注意 :

① 当str_rm为空的情况时,默认删除空白符(包括'\n', '\r', '\t', ' ')

代码演示:

a = ' 123'
print(a.strip())
b='\t\tabc'
print(b)
c = 'sdff\r\n'
print(c.strip())

输出结果:

'123'
'abc'
'sdff'

② str_rm删除序列是只要首尾的字符在删除序列内,就会被删除掉。

代码演示:

a = '123abc'
print(a.strip('21'))
print(a.strip('12'))

输出结果:

'3abc'
'3abc'
十分钟掌握python高效操作字符串的函数

replace()方法

概念:replace() 方法把字符串中的 旧字符(old) 替换成 新字符串(new) ,如果指定第三个参数max,则代表替换次数不超过 max 次。

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

参数:

old —— 将被替换的子字符串。

new —— 新字符串,用于替换old子字符串。

max —— 可选字符串, 替换不超过 max 次

返回值:返回字符串中的 旧字符串(old) 替换成 新字符串(new) 后生成的新字符串,如果指定第三个参数max,则替换不超过 max 次。

栗子:

代码演示:

str = "This is info"
print ("小编 旧 笔名:", str)
print ("小编 新 笔名:", str.replace("info", "InfoNan"))
 
str = "this is a old string example for replace"
print (str.replace("old", "new", 2))
 

输出结果:

小编 旧 笔名:This is info
小编 新 笔名:This is InfoNan

this is a new string example for replace
十分钟掌握python高效操作字符串的函数

需要学习Python的朋友可以私信小编,私信回复“资料”,即可免费领取小编整理的一套Python零基础入门资料。

十分钟掌握python高效操作字符串的函数


分享到:


相關文章: