溫馨提示×

python join函數(shù)的用法是什么

小億
89
2023-11-16 11:11:19
欄目: 編程語言

join()函數(shù)是一個字符串方法,用于將字符串序列中的元素連接成一個新的字符串。它的語法格式如下:

new_string = separator.join(sequence)

其中,separator是一個字符串,用于指定元素之間的分隔符,而sequence是一個字符串序列,可以是列表、元組、或者其他可迭代對象。

join()方法會遍歷序列中的元素,將它們以指定的分隔符連接起來,生成一個新的字符串。分隔符將會插入在相鄰元素之間,而不會放在序列的開頭或結(jié)尾。

以下是一些使用join()函數(shù)的示例:

words = ['Hello', 'world', '!']
sentence = ' '.join(words)
print(sentence)  # 輸出: Hello world !

numbers = ['1', '2', '3', '4']
number_string = '-'.join(numbers)
print(number_string)  # 輸出: 1-2-3-4

message = ('Python', 'is', 'awesome')
full_message = ' '.join(message)
print(full_message)  # 輸出: Python is awesome

需要注意的是,join()方法只能用于字符串序列,如果序列中包含非字符串元素,需要先將其轉(zhuǎn)換成字符串才能使用join()

0