Python中strip方法的妙用

【开胃小菜】

当提到python中strip方法,想必凡接触过python的同行都知道它主要用来切除空格。有以下两种方法来实现。

方法一:用内置函数

#<python>

if __name__ == ‘__main__‘:

str = ‘ Hello world ‘

print ‘[%s]‘ %str.strip()

#</python>

方法二:调用string模块中方法

#<python>

import string

if __name__ == ‘__main__‘:

str = ‘ Hello world ‘

print ‘[%s]‘ %string.strip(str)

#</python>

不知道大家是否知道这两种调用有什么区别?以下是个人一些看法

?  str.strip()是调用python的内置函数,string.strip(str)是调用string模块中的方法

?  string.strip(str)是在string模块定义的。而str.strip()是在builtins模块中定义的

问题一: 如何查看一个模块中方法是否在内置模块有定义?

用dir(模块名)看是否有‘__builtins__‘属性。

例如:查看string模块

#<python> print dir(string)
#</python>

问题二、如何查看python中所有的内置函数

#<python>

print dir(sys.modules[‘__builtin__‘])

#</python>

问题三、如何查看内置模块中内置函数定义

#<python> print help(__builtins__) 
#</python>

以上一些都是大家平时都知道的,接下来就进入本文的主题:

 

【饭中硬菜】

首先请大家看一下下列程序的运行结果:

#<python>

if __name__ == ‘__main__‘:

str = ‘hello world‘

print str.strip(‘hello‘)

print str.strip(‘hello‘).strip()

print str.strip(heldo).strip()   
#sentence 1

stt = ‘h1h1h2h3h4h‘

print stt.strip(‘h1‘)               
#sentence 2

s =‘123459947855aaaadgat134f8sfewewrf7787789879879‘

print s.strip(‘0123456789‘)        
#sentence 3

#</python>

结果见下页:

运行结果:

world

world

wor

2h3h4

aaaadgat134f8sfewewrf

你答对了吗?O(∩_∩)O~

如果你都答对了,在此处我奉上32个赞 …

结果分析:

首先我们查看一下string模块中的strip源码:

#<python>

# Strip leading and trailing tabs and spaces

def strip(s, chars=None):

"""strip(s [,chars]) -> string

    Return a copy of the string swith leading and trailing

    whitespace removed.

    If chars is given and not None,remove characters in chars instead.

    If chars is unicode, S will beconverted to unicode before stripping.

    """

returns.strip(chars)

#</python>

冒昧的翻译一下: 该方法用来去掉首尾的空格和tab。返回一个去掉空格的S字符串的拷贝。如果参数chars不为None有值,那就去掉在chars中出现的所有字符。如果chars是unicode,S在操作之前先转化为unicode.

下面就上面里子中的sentence1 \2 \3做个说明:

#<python>

str = ‘hello world‘

print str.strip(heldo).strip()

#</python>

result:wor

执行步骤:

elloworld

lloworld

oworld

oworl

worl

wor

wor

具体代码执行流程:

#<python>

print str.strip(‘h‘)

print str.strip(‘h‘).strip(‘e‘)

print str.strip(‘h‘).strip(‘e‘).strip(‘l‘)

print str.strip(‘h‘).strip(‘e‘).strip(‘l‘).strip(‘d‘)

print str.strip(‘h‘).strip(‘e‘).strip(‘l‘).strip(‘d‘).strip(‘o‘)

print str.strip(‘h‘).strip(‘e‘).strip(‘l‘).strip(‘d‘).strip(‘o‘).strip(‘l‘)

printstr.strip(‘h‘).strip(‘e‘).strip(‘l‘).strip(‘d‘).strip(‘o‘).strip(‘l‘).strip()

#</python>

不知道你是否看懂其中的奥妙,我是在项目经理陕奋勇帮助下,一起才发现这个规律。

现在稍微总结一下:

s.strip(chars)使用规则:

首先遍历chars中的首个字符,看看在S中是否处于首尾位置,如果是就去掉。把去掉后的新字符串设置为s,继续循环,从chars中的首个字符开始。如果不在,直接从chars第二个字符开始。一直循环到,s中首尾字符都不在chars中,则循环终止。

关键点:查看chars中字符是否在S中首尾

看完这个方法发现python源码开发人员太牛X了,这么经典算法都想的出。

【饭后糕点】

这个方法主要应用于按照特定规则去除两端的制定字符。如果sentence3就是个很好的应用。

例如: 截取字符串中两端数字,或者获取特性字符第一次和最后一次出现之间的字符串等等。

Python中strip方法的妙用,布布扣,bubuko.com

时间: 2024-08-25 22:06:59

Python中strip方法的妙用的相关文章

python中strip()方法学习笔记

Python strip() 方法用于移除字符串头尾指定的字符(默认为空格). 当使用strip('xxx'),只要字符串头尾有"xxx"中的一个,就会去掉,而不是符合字符串''xxx''才去掉 1 >>> string = 'aaabbbccc' 2 >>> string.strip('abc') 3 '' 4 >>> string2 = 'aaaffbbcc' 5 >>> string2.strip('abc'

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用于去除左边的字符,r

Python中__init__方法

注意1.__init__并不相当于C#中的构造函数,执行它的时候,实例已构造出来了. 1 2 3 4 5 class A(object):     def __init__(self,name):         self.name=name     def getName(self):         return 'A '+self.name 当我们执行 1 a=A('hello') 时,可以理解为 1 2 a=object.__new__(A) A.__init__(a,'hello')

python 中特殊方法简写方式

##python 中特殊方法简写方式 class Test: __call__ = lambda *args: args[1] * 2 #这里需要注意lambda的参数 会默认将实例self 加进去 __str__ = lambda self: 'that`s useful...%s' % self.__class__.__name__ t = Test() print(t) print(t(10)) 原文地址:https://www.cnblogs.com/alplf123/p/1029388

python中defaultdict方法的使用

默认值可以很方便 众所周知,在Python中如果访问字典中不存在的键,会引发KeyError异常(JavaScript中如果对象中不存在某个属性,则返回undefined).但是有时候,字典中的每个键都存在默认值是非常方便的.例如下面的例子: strings = ('puppy', 'kitten', 'puppy', 'puppy', 'weasel', 'puppy', 'kitten', 'puppy') counts = {} for kw in strings: counts[kw]

python中__unicode__方法的使用

python中__unicode__(self):方法: __unicode()方法告诉python如何实现对象的unicode表示.如以下数据模型:class Host(models.Model):    id = models.AutoField(primary_key=True)    ip = models.CharField('IP地址', max_length=16, blank=True, null=True)    name = models.CharField('主机名称',

[小知识]Python中__call__方法 @ Python

python中的__call__方法可以把class当做函数调用.例程如下: #coding=utf-8 class A(object): def __init__(self, x): self.x = x def __call__(self, y): return self.x * y C = A(10) #C这个instance可以当做函数来调用 print C(5) # 50

Python中__new__()方法的使用和实例化

new()是在新式类中新出现的方法,它作用在构造方法init()建造实例之前,可以这么理解,在Python 中存在于类里面的构造方法init()负责将类的实例化,而在init()调用之前,new()决定是否要使用该init()方法,因为new()可以调用其他类的构造方法或者直接返回别的对象来作为本类 的实例. 如果将类比喻为工厂,那么init()方法则是该工厂的生产工人,init()方法接受的初始化参 数则是生产所需原料,init()方法会按照方法中的语句负责将原料加工成实例以供工厂出货.而 n

Python中私有方法和私有属性

1.私有方法和私有属性私有方法只能在类内部被调用,不能被对象使用私有属性只能在类内部使用,不能被对象使用 私有属性只能在类内部使用,对象不能使用,但是,我们可以通过在类内部定义公有方法对私有属性进行调用或修改,然后对象在调用这个公有方法使用.###私有属性和私有方法#########在属性名和方法名前面加上 __ class Person(object): def __init__(self): # 公有属性 self.name = "李四" #私有属性 self.__age = 18