English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutorial básico do Python

Controle de fluxo do Python

Função do Python

Tipos de Dados do Python

Operação de arquivo do Python

Objetos e classes do Python

Data e hora do Python

Conhecimento avançado do Python

Manual de referência do Python

Uso e exemplos do join() da string Python

Python string methods

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)

Parâmetro do join()

O método join() aceita um objeto iterável-Objetos que podem retornar seus membros uma vez

Alguns exemplos de iteráveis são:

Retorno do join()

O método join() retorna uma string concatenada com os elementos do iterable.

If the Iterable contains any non-string values, it will triggerTypeErrorException.

Example1:How the join() method works?

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

Example2:How to use the join() method in sets?

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.

Example3:How to use the join() method in dictionaries?

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. 

Python string methods