博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python3 字符串的 strip 函数深入理解
阅读量:4230 次
发布时间:2019-05-26

本文共 1173 字,大约阅读时间需要 3 分钟。

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

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

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

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

    本文通过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      if len(temp_str)==0:         return temp_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_strtest_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.c

 

转载地址:http://dsjqi.baihongyu.com/

你可能感兴趣的文章
C# Programmer's Handbook
查看>>
Constructing Accessible Web Sites
查看>>
Linux Smart Homes For Dummies
查看>>
Building an ASP.NET Intranet
查看>>
Automating UNIX and Linux Administration
查看>>
Advanced C# Programming
查看>>
The Java(TM) Tutorial: A Short Course on the Basics (3rd Edition)
查看>>
Solaris(TM) Performance and Tools: DTrace and MDB Techniques for Solaris 10 and OpenSolaris
查看>>
Unicode Explained
查看>>
Essential C# 2.0
查看>>
Eric Sink on the Business of Software
查看>>
LPI Linux Certification in a Nutshell
查看>>
ATL Internals: Working with ATL 8 (2nd Edition)
查看>>
Programming Sudoku
查看>>
Collaborative Geographic Information Systems
查看>>
The Definitive Guide to the .NET Compact Framework
查看>>
Java 2 Platform, Enterprise Edition: Platform and Component Specifications
查看>>
C++ Coding Standards: 101 Rules, Guidelines, and Best Practices
查看>>
Access VBA Programming
查看>>
Data Entry and Validation with C# and VB. NET Windows Forms
查看>>