我们已经学习了很多字符串变量提供的方法,如 split()、join()、find()、index() 等,但这远远不是它的全部方法。今天给大家列举一些最常用的方法。
Python非常方便,它不需要用户查询文档,只需掌握如下两个帮助函数,即可查看 Python 中的所有函数(方法)以及它们的用法和功能:dir():列出指定类或模块包含的全部内容(包括函数、方法、类、变量等)。help():查看某个函数或方法的帮助文档。
例如,要查看字符串变量(它的类型是 str 类型)所能调用的全部内容,可以在交互式解释器中输入如下命令:
>>>dir(str) ['__add__','__class__','__contains__','__delattr__','__dir__','__doc__','__eq__','__format__','__ge__', '__getattribute__','__getitem__','__getnewargs__','__gt__','__hash__','__init__','__init_subclass__', '__iter__','__le__','__len__','__lt__','__mod__','__mul__','__ne__','__new__','__reduce__', '__reduce_ex__','__repr__','__rmod__','__rmul__','__setattr__','__sizeof__','__str__', '__subclasshook__','capitalize','casefold','center','count','encode','endswith','expandtabs', 'find','format','format_map','index','isalnum','isalpha','isdecimal','isdigit','isidentifier', 'islower','isnumeric','isprintable','isspace','istitle','isupper','join','ljust','lower', 'lstrip','maketrans','partition','replace','rfind','rindex','rjust','rpartition','rsplit', 'rstrip','split','splitlines','startswith','strip','swapcase','title','translate','upper', 'zfill'] >>>
上面列出了字符串类型(str)提供的所有方法,其中以“_”开头、“_”结尾的方法被约定成私有方法,不希望被外部直接调用。
如果希望查看某个方法的用法,则可使用 help() 函数。例如,在交互式解释器中输入如下命令:
>>>help(str.title) Helponmethod_descriptor: title(...) S.title()->str ReturnatitlecasedversionofS,i.e.wordsstartwithtitlecase characters,allremainingcasedcharactershavelowercase. >>>
从上面介绍可以看出,title() 方法的使用形式是“str.title()”,其功能是将字符串中所有单词的首字母大写,其他所有字符全部改为小写。
通过使用 dir() 和 help() 函数,我们就可以查看字符串变量所能调用的所有方法,包括他们的使用方法和功能等。
下一篇