Python join()方法:合并字符串及 dir()和help()帮助函数

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

join() 方法也是非常重要的字符串方法,它是 split() 方法的逆方法,用来将列表(或元组)中包含的多个字符串连接成一个字符串。

使用 join() 方法合并字符串时,它会将列表(或元组)中多个字符串采用固定的分隔符连接在一起。例如,字符串“c.biancheng.net”就可以看做是通过分隔符“.”将 ['c','biancheng','net'] 列表合并为一个字符串的结果。
join() 方法的语法格式如下:

newstr = str.join(iterable)

此方法中各参数的含义如下:

newstr:表示合并后生成的新字符串;

str:用于指定合并时的分隔符;

iterable:做合并操作的源字符串数据,允许以列表、元组等形式提供。

【例 1】将列表中的字符串合并成一个字符串。

>>> list = ['c','biancheng','net']
>>> '.'.join(list)
'c.biancheng.net'

【例 2】将元组中的字符串合并成一个字符串。

>>> dir = '','usr','bin','env'
>>> type(dir)
<class 'tuple'>
>>> '/'.join(dir)
'/usr/bin/env'

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

 

我们已经学习了很多字符串变量提供的方法,如 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)
Help on method_descriptor:

title(...)
    S.title() -> str
   
    Return a titlecased version of S, i.e. words start with title case
    characters, all remaining cased characters have lower case.

>>>

从上面介绍可以看出,title() 方法的使用形式是“str.title()”,其功能是将字符串中所有单词的首字母大写,其他所有字符全部改为小写。
通过使用 dir() 和 help() 函数,我们就可以查看字符串变量所能调用的所有方法,包括他们的使用方法和功能等。