English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
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)
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 :
Types de données natifs - Liste,Tupple,Chaîne,DictionnaireetEnsemble
Objet fichier et utilisation__iter __()ou l'objet défini par la méthode __getitem__()
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.
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
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.