Python字符串strip、lstrip和rstrip方法详解与示例
本文详细介绍Python中字符串的strip、lstrip和rstrip方法。通过示例说明如何去除字符串两端的指定字符集,并强调未传参时默认去除空格的行为。对比三个方法的执行结果,帮助开发者掌握字符串清洗技巧。
复制代码 代码如下:
theString = 'saaaay yes no yaaaass'
print theString.strip('say')
变量theString会依次从首尾移除属于['s','a','y']集合的字符,直至遇到集合外的字符。因此,最终输出结果为:
yes no
逻辑相对直观,lstrip和rstrip的实现原理与此相同。需注意的是,若调用时未传入任何参数,系统将默认去除字符串首尾的空格。
复制代码 代码如下:
theString = 'saaaay yes no yaaaass'
print theString.strip('say')
print theString.strip('say ') #注意'say'后包含空格
print theString.lstrip('say')
print theString.rstrip('say')
运行结果如下:
yes no
es no
yes no yaaaass
saaaay yes no
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









