Python字符串 join() 方法
Python String join() 方法是一个字符串方法,它返回一个字符串,其中序列的元素已通过 str 分隔符连接。
Syntax:
string_name.join(iterable)
Parameters:
The join() method takes iterable – objects capable of returning their members one at a time. Some examples are List, Tuple, String, Dictionary, and Set
Return Value:
The join() method returns a string concatenated with the elements of iterable.
Type Error:
If the iterable contains any non-string values, it raises a TypeError exception.
示例 1:join() 方法的工作
Python
# Python program to demonstrate the
# use of join function to join list
# elements with a character.
list1 = ['1','2','3','4']
s = "-"
# joins elements of list1 by '-'
# and stores in string s
s = s.join(list1)
# join use to join a list of
# strings to a separator s
print(s)
Python
# Python program to demonstrate the
# use of join function to join list
# elements without any separator.
# Joining with empty separator
list1 = ['g','e','e','k', 's']
print("".join(list1))
输出:
1-2-3-4
示例 2:使用空字符串连接
Python
# Python program to demonstrate the
# use of join function to join list
# elements without any separator.
# Joining with empty separator
list1 = ['g','e','e','k', 's']
print("".join(list1))
输出:
geeks