2022年 11月 5日

python中strip的使用

今天聊聊python去除字符串空格的函数:strip()和replace()
1.strip():
函数功能描述:Python strip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。
注意:该方法只能删除开头或是结尾的字符,不能删除中间部分的字符。
格式:str.strip([char])。其中,str为待处理的字符,char指定去除的源字符串首尾的字符。
返回结果:去除空格时候的新字符串。
示例:

	str = "00000003210Runoob01230000000"
	print str.strip( '0' ) # 去除首尾字符 0
	
	 结果:3210Runoob0123

	str2 = "   Runoob      "  # 去除首尾空格
	print str2.strip()
	
	结果:Runoob
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

2.replace()
函数功能描述:Python replace() 方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次

格式:str.replace(old, new[, max]),参数在函数功能描述中已经说明。
返回值:返回字符串中的 old(旧字符串) 替换成 new(新字符串)后生成的新字符串,如果指定第三个参数max,则替换不超过 max 次。

示例:

str = "this is string example....wow!!! this is really string"
print str.replace("is", "was")
print str.replace("is", "was", 3)

结果:
thwas was string example....wow!!! thwas was really string
thwas was string example....wow!!! thwas is really string
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

同样可以采用replace实现空格的去除。举个例:

	"  x y z  ".replace(' ', '')   # returns "xyz" 	
  • 1

在这里插入图片描述