English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
join() é um método de string que retorna uma string conectada com os elementos do iterable.
O método join() oferece uma maneira flexível de conectar strings. Ele conecta cada elemento iterável (como lista, string e tupla) a uma string e retorna a string conectada.
A sintaxe do join() é:
string.join(iterable)
O método join() aceita um objeto iterável-Objetos que podem retornar seus membros uma vez
Alguns exemplos de iteráveis são:
Tipos de dados nativos - Lista,Tupla,String,DicionárioeConjunto
Objeto de arquivo e uso__iter __()ou objeto definido pelo método __getitem__()
O método join() retorna uma string concatenada com os elementos do iterable.
If the Iterable contains any non-string values, it will triggerTypeErrorException.
numList = ['1', '2', '3', '4'] seperator = ', ' print(seperator.join(numList)) numTuple = ('1', '2', '3', '4) print(seperator.join(numTuple)) s1 = 'abc' s2 = '123" """ s2each character is connected to s1的前面""" print('s1.join(s2):, s1.join(s2)) """ s1each character is connected to s2的前面""" print('s2.join(s1):, s2.join(s1))
When running the program, the output is:
1, 2, 3, 4 1, 2, 3, 4 s1.join(s2): 1abc2abc3 s2.join(s1): a123b123c
test = { '2', '1', '3} s = ', ' print(s.join(test)) test = {'Python', 'Java', 'Ruby'} s = '->-" print(s.join(test))
When running the program, the output is:
2, 3, 1 Python->->Ruby->->Java
Note: Sets are an unordered collection of items, and you may get different outputs.
test = { 'mat': 1, 'that': 2"} s = '-" print(s.join(test)) test = {1: 'mat', 2: 'that'} s = ', ' # This throws an error print(s.join(test))
When running the program, the output is:
mat->that Traceback (most recent call last): File "...", line 9, in <module> TypeError: sequence item 0: expected str instance, int found
The join() method tries to concatenate the keys of the dictionary (not the values) to the string. If the string key is not a string, it will triggerTypeErrorException.