python中strip的使⽤
今天聊聊python去除字符串空格的函数:strip()和replace()
1.strip():
函数功能描述:Python strip() ⽅法⽤于移除字符串头尾指定的字符(默认为空格或换⾏符)或字符序列。
注意:该⽅法只能删除开头或是结尾的字符,不能删除中间部分的字符。
字符串replace函数格式:str.strip([char])。其中,str为待处理的字符,char指定去除的源字符串⾸尾的字符。
返回结果:去除空格时候的新字符串。
⽰例:
str = "00000003210Runoob01230000000"
print str.strip( '0' ) # 去除⾸尾字符 0
结果:3210Runoob0123
str2 = "  Runoob      "  # 去除⾸尾空格
print str2.strip()
结果:Runoob
函数功能描述:Python replace() ⽅法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过max 次
格式:place(old, new[, max]),参数在函数功能描述中已经说明。
返回值:返回字符串中的 old(旧字符串) 替换成 new(新字符串)后⽣成的新字符串,如果指定第三个参数max,则替换不超过 max 次。
⽰例:
str = "this is wow this is really string"
place("is", "was")
place("is", "was", 3)
结果:
thwas was wow thwas was really string
thwas was wow thwas is really string
同样可以采⽤replace实现空格的去除。举个例:
"  x y z  ".replace(' ', '')  # returns "xyz"

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。