利用切片操作,实现函数,去除字符串首尾的0

此例使用strip()方法可以很轻松的实现,这个代码旨在熟悉切片的操作。

Python strip()方法
用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。
注意:该方法只能删除开头或是结尾的字符,不能删除中间部分的字符。
语法
strip()方法语法:
str.strip([chars]);
参数
chars    移除字符串头尾指定的字符序列。
返回值

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

python实现的代码如下:

def trim(s):
#第一个for循环去除字符串前面的0
	for i in s:
		if i == '0':
			s = s[1 : len(s)]
		else:
			break
#第二个for循环去除字符串后面的0
	for i in range(1, len(s)):
		if s[-1] == '0':
			s = s[0 : len(s) - 1]
		else:
			break
	print(s)

if __name__ == "__main__":
	trim('000000python000')

猜你喜欢

转载自blog.csdn.net/lsy_07/article/details/80735128