当前位置:首页 > 行业动态 > 正文

python join列表

使用 join()方法可以将列表中的元素连接成一个字符串。 ', '.join(['a', 'b', 'c']) 结果为 'a, b, c'。

Python列表的join()函数用于将列表中的元素连接成一个字符串,它接受一个可选参数,即分隔符,用于在连接的元素之间插入指定的字符或字符串。

python join列表  第1张

以下是join()函数的详细用法:

1、基本用法:

“`python

list = [‘a’, ‘b’, ‘c’]

result = ”.join(list)

print(result)

“`

输出结果为:abc

2、使用分隔符:

“`python

list = [‘apple’, ‘banana’, ‘cherry’]

result = ‘, ‘.join(list)

print(result)

“`

输出结果为:apple, banana, cherry

3、指定分隔符为空字符串:

“`python

list = [‘hello’, ‘world’]

result = ”.join(list)

print(result)

“`

输出结果为:helloworld

4、指定分隔符为其他字符串:

“`python

list = [‘apple’, ‘banana’, ‘cherry’]

result = ”.join(list)

print(result)

“`

输出结果为:applebananacherry

5、指定分隔符为多个字符:

“`python

list = [‘apple’, ‘banana’, ‘cherry’]

result = ”.join(list)

print(result)

“`

输出结果为:applebananacherry

6、指定分隔符为非字符串类型:

“`python

list = [1, 2, 3]

result = ”.join(map(str, list))

print(result)

“`

输出结果为:123

0