首页 / 教程

Python join()函数用法

时间:2024-01-12 10:20:51阅读:0

Python join()函数用法

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

join()函数参数

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

join()函数返回值

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

join()函数用法实例

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

>>> join('ABC')Traceback (most recent call last):  File "", line 1, in NameError: name 'join' is not defined>>> ' '.join('ab','c')Traceback (most recent call last):  File "", line 1, in TypeError: join() takes exactly one argument (2 given)>>> ' '.join([1,2])Traceback (most recent call last):  File "", line 1, in 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('Python')'Python'>>> ','.join('编程语言')'编程语言'>>> ','.join(['Python编程语言','www.59py.com','python全栈教程'])'Python编程语言,www.59py.com,python全栈教程'


本站文章均来自互联网,仅供学习参考,如有侵犯您的版权,请邮箱联系我们删除!

猜你喜欢

  • Python ljust()函数用法字字符串

    Python ljust()函数用法

    Python字符串ljust()方法返回长度为width的左对齐的字符串。使用指定的fillchar(默认为空格)填充完成。 如果宽度小于len(s),则返回原始字符串。  ljust()语法  以下是ljust()方法的语法:str.lj...

    2024-01-12 字字符串
  • Python lower()函数用法字字符串

    Python lower()函数用法

    Python中,lower()是一个常用的字符串方法。它能够将字符串中所有大写字母转换为小写字母。下面,我们将从以下几个方面对lower()函数进行详细的阐述。  lower()用法str.lower()  按照上述基本语法,通过调用str...

    2024-01-12 字字符串
  • Python maketrans()函数用法字字符串

    Python maketrans()函数用法

    Python中的maketrans()方法用于创建字符映射的转换表,用指定字符列表来一一对应需要被替换的字符列表,然后可以创建一个类似英汉互译的对应关系。  maketrans()语法  str.maketrans(str1, str2) ...

    2024-01-12 字字符串