python trim函数_python strip()函数 介绍
描述
Python strip() 方法用于移除字符串頭尾指定的字符(默認為空格)。
語法
strip()方法語法:
str.strip([chars]);
參數
chars -- 移除字符串頭尾指定的字符。
返回值
返回移除字符串頭尾指定的字符生成的新字符串。
實例
以下實例展示了strip()函數的使用方法:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
str = "0000000 jb51.net 0000000"
print(str.strip( '0' )) # 去除首尾字符 0
str2 = " jb51.net " # 去除首尾空格
print(str2.strip())
以上實例輸出結果如下:
jb51.net
jb51.net
Python3 replace()方法
描述
replace() 方法把字符串中的 old(舊字符串) 替換成 new(新字符串),如果指定第三個參數max,則替換不超過 max 次。
語法
replace()方法語法:
str.replace(old, new[, max])
參數
old -- 將被替換的子字符串。
new -- 新字符串,用于替換old子字符串。
max -- 可選字符串, 替換不超過 max 次
返回值
返回字符串中的 old(舊字符串) 替換成 new(新字符串)后生成的新字符串,如果指定第三個參數max,則替換不超過 max 次。
實例
以下實例展示了replace()函數的使用方法:
#!/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))
以上實例輸出結果如下:
腳本之家舊地址: www.jbzj.com
腳本之家新地址: www.jb51.net
thwas was string example....wow!!!
函數原型
聲明:s為字符串,rm為要刪除的字符序列
s.strip(rm) 刪除s字符串中開頭、結尾處,位于 rm刪除序列的字符
s.lstrip(rm) 刪除s字符串中開頭處,位于 rm刪除序列的字符
s.rstrip(rm) 刪除s字符串中結尾處,位于 rm刪除序列的字符
注意:
1. 當rm為空時,默認刪除空白符(包括'\n', '\r', '\t', ' ')
例如:
>>> a = ' 123'
>>> a.strip()
'123'
>>> a='\t\tabc'
'abc'
>>> a = 'sdff\r\n'
>>> a.strip()
'sdff'
2.這里的rm刪除序列是只要邊(開頭或結尾)上的字符在刪除序列內,就刪除掉。
例如 :
>>> a = '123abc'
>>> a.strip('21')
'3abc' 結果是一樣的
>>> a.strip('12')
'3abc'
文章就到這了,需要的朋友可以參考一下
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的python trim函数_python strip()函数 介绍的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python收取wss数据_Python
- 下一篇: 平安银行信用卡提示虚构交易