当前位置: 首页 > 图灵资讯 > 行业资讯> Python dir()和help()帮助函数

Python dir()和help()帮助函数

发布时间:2025-10-19 21:21:16

我们学习了很多字符串变量提供的方法,比如 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() 函数,我们可以查看字符串变量可以调用的所有方法,包括它们的使用方法和功能。

相关文章

Python dir()和help()帮助函数

Python dir()和help()帮助函数

2025-10-19
Python如何求解最长公共子序列

Python如何求解最长公共子序列

2025-10-19
Python startswith()和endswith()方法

Python startswith()和endswith()方法

2025-10-19
python如何通过日志分析加入黑名单

python如何通过日志分析加入黑名单

2025-10-17
python抽象基类之_subclasshook_方法

python抽象基类之_subclasshook_方法

2025-10-17
Python3 面向对象

Python3 面向对象

2025-10-17