python文本处理的函数总结

就刚刚写的程序中,用到了map、strip和split函数

下面对这几个函数重新认识一下:

strip函数:这个函数是字符串的方法

help(str.strip)之后

返回:

strip(...)
    S.strip([chars]) -> str
    
    Return a copy of the string S with leading and trailing
    whitespace removed.
    If chars is given and not None, remove characters in chars instead.

下面写几个示例看看:

可以看出,中间的换行符并没有去除,但是末尾的就被去除了,换行符本质上就是空白嘛,所以这里的S是可以去掉换行符的。

下面看看split,这个函数是字符串的方法。

python文档是这样的:

split(...)
    S.split(sep=None, maxsplit=-1) -> list of strings
    
    Return a list of the words in S, using sep as the
    delimiter string.  If maxsplit is given, at most maxsplit
    splits are done. If sep is not specified or is None, any
    whitespace string is a separator and empty strings are
    removed from the result.

通过指定分隔符对字符串进行切片,如果参数maxsplit有指定值,则仅分隔maxsplit个子字符串

这里的sep默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等

示例:

map函数

python文档:

class map(object)
 |  map(func, *iterables) --> map object
 |  
 |  Make an iterator that computes the function using arguments from
 |  each of the iterables.  Stops when the shortest iterable is exhausted.
 |  
 |  Methods defined here:
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __iter__(self, /)
 |      Implement iter(self).
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  __next__(self, /)
 |      Implement next(self).
 |  
 |  __reduce__(...)
 |      Return state information for pickling.

这个文档太复杂了看不懂,看看别人怎么说:

map(function, iterable, ...)

map()是python内置的高阶函数,它接受一个函数f 和一个 list,并通过函数 f依次作用在list的每一个元素上,得到一个可迭代对象

这个可迭代对象长这样:

但是可以看见,让list转化之后就可以了。

猜你喜欢

转载自blog.csdn.net/weixin_39523628/article/details/81200702