使用内置函数strip去掉首尾空格
1. strip()函数
- Python strip() 方法用于移除字符串头尾指定的字符(默认为空格)或字符序列。
- 注意:该方法只能删除开头或是结尾的字符,不能删除中间部分的字符。
- 菜鸟教程:https://www.runoob.com/python3/python3-string-strip.html
2. 代码实例
#!/user/bin/env python3
# -*- coding: utf-8 -*-
# 例子1(去掉首尾空格)
str1 = " hello hi andbbddbdbdb "
print (str1.strip( ' ' )) # 指定字符串:空格(默认就是空格)
# 例子2(去掉指定字符串)
str2 = "*****this is **string** example....wow!!!*****"
print (str2.strip( '*' )) # 指定字符串:*
# 例子3(去掉指定字符序列)
str3 = "123abcrunoob321"
print (str3.strip( '12' )) # 指定字符序列为:12
'''
输出结果为:
hello hi andbbddbdbdb
this is **string** example....wow!!!
3abcrunoob3
'''
参考:
https://blog.csdn.net/lanyangyang0103/article/details/89313275 python 去掉首尾空格