新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
創(chuàng)新互聯(lián)Python教程:Pythonjoin()
python 中的join()函數(shù)通過使用字符串分隔符連接給定 iterable 的所有元素來幫助創(chuàng)建新字符串。

成都創(chuàng)新互聯(lián)公司網(wǎng)站建設(shè)公司,提供成都網(wǎng)站制作、成都網(wǎng)站建設(shè)、外貿(mào)營銷網(wǎng)站建設(shè),網(wǎng)頁設(shè)計,建網(wǎng)站,PHP網(wǎng)站建設(shè)等專業(yè)做網(wǎng)站服務(wù);可快速的進行網(wǎng)站開發(fā)網(wǎng)頁制作和功能擴展;專業(yè)做搜索引擎喜愛的網(wǎng)站,是專業(yè)的做網(wǎng)站團隊,希望更多企業(yè)前來合作!
**string.join(iterable)** #where iterable may be List, Tuple, String, Dictionary and Set.
join()參數(shù):
join()函數(shù)接受一個參數(shù)。如果可迭代表包含任何非字符串值,該函數(shù)將引發(fā)類型錯誤異常,
| 參數(shù) | 描述 | 必需/可選 |
|---|---|---|
| 可迭代的 | 所有返回值都是字符串的任何可迭代對象 | 需要 |
join()返回值
返回值始終是串聯(lián)字符串。如果我們使用字典作為可迭代表,返回值將是鍵,而不是值。
| 投入 | 返回值 | | 可重復(fù)的 | 線 |
Python 中join()方法的示例
示例join()方法在 Python 中是如何工作的?
# .join() with lists
List = ['5', '4', '3', '2']
separator = ', '
print(separator.join(List))
# .join() with tuples
Tuple = ('5', '4', '3', '2')
print(separator.join(Tuple))
string1 = 'xyz'
string2 = '123'
# each element of string2 is separated by string1
# '1'+ 'xyz'+ '2'+ 'xyz'+ '3'
print('string1.join(string2):', string1.join(string2))
# each element of string1 is separated by string2
# 'x'+ '123'+ 'y'+ '123'+ 'z'
print('string2.join(string1):', string2.join(string1))
輸出:
5, 4, 3, 2
5, 4, 3, 2
string1.join(string2): 1xyz2xyz3
string2.join(string1): x123y123z 示例join()方法如何在 Python 中處理集合?
# .join() with sets
num = {'5', '4', '3'}
separator = ', '
print(separator.join(num))
string = {'Apple', 'Orange', 'Grapes'}
separator = '->->'
print(separator.join(string))
輸出:
5, 4, 3
Apple->->Orange->->Grapes 示例 2:傳遞超出范圍的整數(shù)
print(chr(-1))
print(chr(1114112))
輸出:
ValueError: chr() arg not in range(0x110000)
ValueError: chr() arg not in range(0x110000) 示例join()方法如何與字典一起工作?
# .join() with dictionaries
dict = {'test': 1, 'with': 2}
seperator = '->'
# joins the keys only
print(seperator.join(dict))
dict = {1: 'test', 2: 'with'}
seperator = ', '
# this gives error since key isn't string
print(seperator.join(dict))
輸出:
test->with
Traceback (most recent call last):
File "...", line 12, in TypeError: sequence item 0: expected str instance, int found 本文題目:創(chuàng)新互聯(lián)Python教程:Pythonjoin()
轉(zhuǎn)載注明:http://www.dlmjj.cn/article/dphgcpg.html


咨詢
建站咨詢
