目錄
join方法的源碼:
列表數據為字符串
列表數據為數字
三引號也可以使用join
join方法的源碼:
def join(self, ab=None, pq=None, rs=None): # real signature unknown; restored from __doc__"""Concatenate any number of strings.The string whose method is called is inserted in between each given string.The result is returned as a new string.Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'"""pass
該方法功能是連接任意數量的字符串。調用其方法的字符串插入到每個給定字符串之間。結果將作為新字符串返回。其中join傳參需要是可迭代的對象如列表、字符串,如果是字符串join會把字符串拆解成單個字符進行拼接如下:
a=['asdasd','dasdasdwww11']
b=''.join(a)
aa='123123'
bb='www'
cc=aa.join(bb)
print(cc)
輸出:w123123w123123w
列表數據為字符串
如果你想將單個列表中的數據拼接成一個字符串,可以使用 `join()` 方法。`join()` 方法將列表中的字符串元素連接起來,并返回一個新的字符串。
下面是一個示例:
my_list = ['Hello', 'World', '!', 'This', 'is', 'Python']
result = ' '.join(my_list)
print(result)
輸出:
```
Hello World ! This is Python
```
在上面的示例中,我們使用空格作為連接符,將列表中的字符串元素連接成一個字符串。你可以根據需要選擇不同的連接符,例如空字符串 `''`、逗號 `','` 等。
" ".join(["space", "string", "joiner"]) == "space string joiner"
輸出:True
"\n".join(["multiple", "lines"]) == "multiple\nlines" == (
"""multiple
lines""")
輸出:True
列表數據為數字
請注意,`join()` 方法只能用于連接字符串元素的列表。如果列表中包含非字符串元素,你需要先將其轉換為字符串才能進行拼接。例如,可以使用 `map()` 函數將列表中的元素轉換為字符串:
my_list = [1, 2, 3, 4, 5]
result = ''.join(map(str, my_list))
print(result)
輸出:
```
12345
```
在上面的示例中,我們使用 `map()` 函數將列表中的整數元素轉換為字符串,然后再使用 `join()` 方法拼接成一個字符串。
三引號也可以使用join
query="\n".join(["select cities.city, state, country"," from cities, venues, events, addresses"," where cities.city like %s"," and events.active = 1"," and venues.address = addresses.id"," and addresses.city = cities.id"," and events.venue = venues.id"])