python strip() 函数探究

枫铃3年前 (2021-07-10)Python253

strip()方法语法:str.strip([chars]);

声明:str为字符串,rm为要删除的字符序列

  • str.strip(rm) 删除字符串中开头、结尾处,位于rm删除序列的字符
eg1:
#首尾端'0'被删除,中间不动
>>> t='0000this is string example0000wow!!!0000'
>>> t.strip('0')
'this is string example0000wow!!!'
eg2:
#无入参,默认删除首尾所有空字符 ‘\n\t空格‘
>>>s='\n 0000this is string example0000wow!!!0000\n \t'
>>> s.strip()
'0000this is string example0000wow!!!0000'
  • str.lstrip(rm) 删除字符串中开头处,位于 rm删除序列的字符
'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:579817333 
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
t='0000this is string example0000wow!!!0000'
>>> t.lstrip('0')
'this is string example0000wow!!!0000' 

#空入参同样可删除首部空字符,'.rstrip()'同理
s='\n 0000this is string example0000wow!!!0000\n \t'
>>> s.lstrip()
'0000this is string example0000wow!!!0000\n \t'
  • str.rstrip(rm) 删除字符串中结尾处,位于 rm删除序列的字符
t='0000this is string example0000wow!!!0000'
>>> t.rstrip('0')
'0000this is string example0000wow!!!'

s='\n 0000this is string example0000wow!!!0000\n \t'
>>> s.rstrip()
'\n 0000this is string example0000wow!!!0000'

究竟何为’首尾’?实验之

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:579817333 
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
s='\n 0000this is string is example0000wow!!!0000\n \t'
>>> s.lstrip('\n 0')
'this is string is example0000wow!!!0000\n \t'
#首部'\n 0000'被删除

>>> s.lstrip('\n 0this')
'ring is example0000wow!!!0000\n \t'

奇妙啊,我的目标是删除首部’\n 0000this’,结果’\n 0000this is st’全被删除,说明:符合入参(’\n 0this’)的字符皆是删除对象,不论字符顺序

但,为何string后面的is没有删除?因为,'首部’指的是’连续符合’入参要求的字符,string中的’r’隔断了入参的连续字符要求,python判定首部结束。

实验证明:

所谓的首、尾,判定依据是-是否连续符合入参要求,如果符合,不论顺序,皆可操作,一直到遇到第一个非入参字符为止.

相关文章

利用python同步windows和linux文件

写python脚本的初衷,每次在windows编辑完文件后,想同步到linux上去,只能够登录服务器,...

爬虫基本原理

爬虫基本原理 一、爬虫是什么? 百度百科和维基百科对网络爬虫的定义:简单来说爬虫就是抓取目标网站内容的工具,一般是根据定义的行...

Django 函数和方法的区别

函数和方法的区别 1、函数要手动传self,方法不用传 2、如果是一个函数,用类名去调用,如果是一个方法...

Django 知识补漏单例模式

单例模式:(说白了就是)创建一个类的实例。在 Python 中,我们可以用多种方法来实现单例模式&#x...

Django基础知识MTV

Django简介 Django是使用Python编写的一个开源Web框架。可以用它来快速搭建一个高性能的网站。 Django也是一个MVC框架。但是在Dj...

Python mysql 索引原理与慢查询优化

一 介绍 为何要有索引? 一般的应用系统,读写比例在10:1左右,而且插入操作和一般的更新操作很少出现性能问题,...

发表评论

访客

看不清,换一张

◎欢迎参与讨论,请在这里发表您的看法和观点。