python strip函数用法_python strip()函数 介绍
描述
Python strip() 方法用于移除字符串頭尾指定的字符(默認(rèn)為空格)。
語法
strip()方法語法:
str.strip([chars]);
參數(shù)
chars -- 移除字符串頭尾指定的字符。
返回值
返回移除字符串頭尾指定的字符生成的新字符串。
實(shí)例
以下實(shí)例展示了strip()函數(shù)的使用方法:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
str = "0000000 jb51.net 0000000"
print(str.strip( '0' )) # 去除首尾字符 0
str2 = " jb51.net " # 去除首尾空格
print(str2.strip())
以上實(shí)例輸出結(jié)果如下:
jb51.net
jb51.net
Python3 replace()方法
描述
replace() 方法把字符串中的 old(舊字符串) 替換成 new(新字符串),如果指定第三個(gè)參數(shù)max,則替換不超過 max 次。
語法
replace()方法語法:
str.replace(old, new[, max])
參數(shù)
old -- 將被替換的子字符串。
new -- 新字符串,用于替換old子字符串。
max -- 可選字符串, 替換不超過 max 次
返回值
返回字符串中的 old(舊字符串) 替換成 new(新字符串)后生成的新字符串,如果指定第三個(gè)參數(shù)max,則替換不超過 max 次。
實(shí)例
以下實(shí)例展示了replace()函數(shù)的使用方法:
#!/usr/bin/python3
str = "歡迎訪問腳本之家www.jb51.net"
print ("腳本之家舊地址:", str)
print ("腳本之家新地址:", str.replace("jb51.net", "jbzj.com"))
str = "this is string example....wow!!!"
print (str.replace("is", "was", 3))
以上實(shí)例輸出結(jié)果如下:
腳本之家舊地址: www.jbzj.com
腳本之家新地址: www.jb51.net
thwas was string example....wow!!!
函數(shù)原型
聲明:s為字符串,rm為要刪除的字符序列
s.strip(rm) 刪除s字符串中開頭、結(jié)尾處,位于 rm刪除序列的字符
s.lstrip(rm) 刪除s字符串中開頭處,位于 rm刪除序列的字符
s.rstrip(rm) 刪除s字符串中結(jié)尾處,位于 rm刪除序列的字符
注意:
1. 當(dāng)rm為空時(shí),默認(rèn)刪除空白符(包括'\n', '\r', '\t', ' ')
例如:
>>> a = ' 123'
>>> a.strip()
'123'
>>> a='\t\tabc'
'abc'
>>> a = 'sdff\r\n'
>>> a.strip()
'sdff'
2.這里的rm刪除序列是只要邊(開頭或結(jié)尾)上的字符在刪除序列內(nèi),就刪除掉。
例如 :
>>> a = '123abc'
>>> a.strip('21')
'3abc' 結(jié)果是一樣的
>>> a.strip('12')
'3abc'
文章就到這了,需要的朋友可以參考一下
總結(jié)
以上是生活随笔為你收集整理的python strip函数用法_python strip()函数 介绍的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python性能解决_Python性能优
- 下一篇: 复杂update_Python 代码判断