join()方法是一種字符串方法,它返回一個字符串,在該字符串中,序列元素已通過str分隔符進行了連接。
用法:
string_name.join(iterable)
string_name:It is the name of string in which
joined elements of iterable will be
stored.
參數:join()方法采用可迭代的對象,這些對象能夠一次返回一個成員。一些示例是列表,元組,字符串,字典和集合
返回值:join()方法返回一個與iterable元素串聯的字符串。
類型錯誤:如果迭代器包含任何非字符串值,則會引發TypeError異常。
以下示例程序旨在說明join()方法的用法:
# 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 sting s
s = s.join(list1)
# join use to join a list of
# strings to a separator s
print(s)
輸出:
1-2-3-4
用空字符串連接。
# 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