join()函数python作用,以特定格式连接字符串

join()函数描述

join()函数,是python中字符串的一个内置方法,常用来以指定的格式连接字符串。join()方法的调用方式比较特殊,如:分隔符.join( 字符串str或元素为str的可迭代对象 )。


join()函数参数

接收一个参数,类型为python的字符串或元素为str的可迭代对象;


join()函数返回值

join()函数返回一个以指定格式连接而成的字符串;


join()函数实例代码

先来看看几种错误的用法:

>>> join('ABC')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'join' is not defined
>>> ' '.join('ab','c')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: join() takes exactly one argument (2 given)
>>> ' '.join([1,2])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sequence item 0: expected str instance, int found

如上代码,1、当不通过.join()的方式对join()进行引用时,python会抛出NameError,并提示name 'join' is not defined,足以见得,join()在python当中并不是一个单独存在的函数;2、当传递两个参数给.join()时,python抛出TypeError,根据提示,可知join()只接收一个参数;3、当传递给.join()的是可迭代对象,如list,但list中的元素却不是字符串时,python也会抛出TypeError。


再来看看join()的一般用法:

>>> ' '.join('笨鸟')
'笨 鸟'
>>> ','.join('工具')
'工,具'
>>> ','.join(['笨鸟工具','x1y1z1.com','python全栈教程'])
'笨鸟工具,x1y1z1.com,python全栈教程'

全栈后端 / python教程 :


























Copyright © 2022-2024 笨鸟工具 x1y1z1.com All Rights Reserved.