浅谈python中截取字符函数strip,lstrip,rstrip
2019/7/13 21:02:40
本文主要是介绍浅谈python中截取字符函数strip,lstrip,rstrip,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
一、起因
今天在做角色控制中,有一个地方用到rstrip,判断用户请求的url是否与数据库对应可用权限中url相符。
if request.path == x.url or request.path.rstrip('/') == x.url: #精确匹配,判断request.path是否与permission表中的某一条相符
借此机会总结一下python中strip,lstrip和rstrip。
二、介绍
Python中strip用于去除字符串的首位字符,同理,lstrip用于去除左边的字符,rstrip用于去除右边的字符。
这三个参数都可以传入一个参数,指定要去除的首尾字符。
需要注意的是,传入的是一个字符数组,编译器去除两端所有匹配的字符,直到没有匹配的字符,比如:
>>> testString="saaaay yes no yaaaass" >>> print testString.strip('say') yes no >>>
可见,testString依次被去除首尾在['s','a','y']数组内的字符,直到剩余字符不再数组内。所以输出yes no。
Note:
当没有传入参数时,默认去除首尾空格。
lstrip和rstrip原理一样。
举例:
>>> testString="saaaay yes no yaaaass" >>> print testString.strip('say') yes no #以空格开头和结尾的 >>> print testString.strip('say ') es no#开头结尾均无空格 >>> print testString.lstrip('say') yes no yaaaass#以空格开头 >>> print testString.rstrip('say') saaaay yes no #以空格结尾 >>>
可以对照编辑器中选中状态的这张图理解
以上所述就是本文的全部内容了,希望大家能够喜欢。
这篇关于浅谈python中截取字符函数strip,lstrip,rstrip的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-08有遇到过吗?同样的规则 Excel 中 比Python 结果大
- 2024-03-30开始python成长之路
- 2024-03-29python optparse
- 2024-03-29python map 函数
- 2024-03-20invalid format specifier python
- 2024-03-18pool.map python
- 2024-03-18threads in python
- 2024-03-14python Ai 应用开发基础训练,字符串,字典,文件
- 2024-03-13id3 algorithm python
- 2024-03-13sum array elements python