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

Tutoriel de base Python

Contrôle de flux Python

Fonction en Python

Types de données en Python

Opérations de fichiers Python

Objets et classes Python

Dates et heures Python

Connaissances avancées Python

Manuel de référence Python

Utilisation et exemples de join() en Python

String methods in Python

join() est une méthode de chaîne qui retourne une chaîne composée des éléments iterable.

La méthode join() fournit une manière flexible de joindre des chaînes. Elle relie chaque élément itérable (comme une liste, une chaîne et un tuple) à une chaîne et retourne la chaîne joints.

La syntaxe de join() est :

string.join(iterable)

Paramètres de join()

La méthode join() utilise un objet itérable-Objets qui peuvent retourner leurs membres en une seule fois

Certains exemples d'itérables sont :

Retour de join()

La méthode join() retourne une chaîne de caractères composée des éléments de l'itérable concatenés.

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

Example1How does the join() method work?

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 s1in front """ 
print('s1.join(s2): ', s1.join(s2))
""" s1each character is connected to s2in front """ 
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

Example2How does the join() method work 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.

Example3How does the join() method work 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. 

String methods in Python