2、strip()
strip()方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。
s = ' hello '.strip()
print(s)
# hello
s = '###hello###'.strip()
print(s)
# ###hello###
在使用strip()方法时,默认去除空格或换行符,所以#号并没有去除。
可以给strip()方法添加指定字符,如下所示。
s = '###hello###'.strip('#')
print(s)
# hello
此外当指定内容不在头尾处时,并不会被去除。
s = ' \n \t hello\n'.strip('\n')
print(s)
#
# hello
s = '\n \t hello\n'.strip('\n')
print(s)
# hello
第一个\n前有个空格,所以只会去取尾部的换行符。
最后strip()方法的参数是剥离其值的所有组合,这个可以看下面这个案例。
s = 'www.baidu.com'.strip('cmow.')
print(s)
# baidu
最外层的首字符和尾字符参数值将从字符串中剥离。字符从前端移除,直到到达一个不包含在字符集中的字符串字符为止。
在尾部也会发生类似的动作。