Python字符串的strip函数深入理解

    一般对字符串的strip函数用得很简单,可能只是偶尔去除字符串两边的空格字符之类,最近遇到其中一个稍微复杂点的应用。比如下面这样的语句,又该怎么去理解呢?

test_str = "www.example.com"
chars = "ow.m"
print(test_str.strip(chars))

    运行输出的字符串结果是:example.c 。

    刚开始的时候对这个结果不是特别理解,不知道这个函数具体的运行步骤是什么,对结果也有点一脸懵逼。经过仔细分析,最后可以得到这个函数的具体作用:只要首尾两端的字符在 chars 之内,就会被删除,直到遇到第一个不在 chars 内的字符(这句话的原文地址为:https://www.cnblogs.com/gl1573/p/9957962.html)。但是,我们该怎么样理解这句话呢?

    本文通过Python定义一个类,并在类里面自定义了一个类似strip的函数,与字符串的strip函数具有类似的功能。由于Python中字符串的strip函数无法直接看到源码,于是希望通过自定义函数来实现与strip函数的相同功能。自我的片面理解,如有不当,还请各位大佬指出。

class ExampleStr:
   def __init__(self, raw_str):
      self.raw_str = raw_str

   def str_strip(self, chars):
      temp_str = self.raw_str
      head_char = temp_str[0]
      tail_char = temp_str[-1]
      while head_char in chars or tail_char in chars:
         if head_char in chars:
            temp_str = temp_str[1:]
         elif tail_char in chars:
            temp_str = temp_str[:-1]
         head_char = temp_str[0]
         tail_char = temp_str[-1]
      return temp_str


test_str = "www.example.com"
str_obj = ExampleStr("www.example.com")
chars = "ow.m"
print(test_str.strip(chars)) # 字符串的strip函数
print(str_obj.str_strip(chars)) # 自定义的模仿strip功能的str_strip函数

    运行结果为:.example.com
 

猜你喜欢

转载自blog.csdn.net/TomorrowAndTuture/article/details/89402397