Python の join() は、文字列区切り文字で区切られたシーケンスの要素を結合するために使用される組み込みの文字列関数です。この関数はシーケンスの要素を結合して文字列にします。
アスキーテーブルJava
Python String join() 構文
構文: separator_string.join(反復可能)
パラメーター:
- Iterable – メンバーを一度に 1 つずつ返すことができるオブジェクト。いくつかの例は次のとおりです リスト、タプル、文字列、辞書 、 とセット
戻り値: join() メソッドは、次の要素を連結した文字列を返します。 反復可能な 。
タイプエラー 注: 反復可能オブジェクトに文字列以外の値が含まれている場合は、TypeError 例外が発生します。
Python の String join() の例
で パイソン 、次のようなさまざまなタイプの反復可能オブジェクトで join() メソッドを使用できます。 リスト 、 タプル 、 弦 、 辞書 、 そして セット 。例を使って一つずつ理解していきましょう。
パイソン # This will join the characters of the string 'hello' with '-' str = '-'.join('hello') print(str) # Output: h-e-l-l-o> 出力:
h-e-l-l-o>
Python でリストを文字列に結合する
ここで私たちは、 リスト join() メソッドを 2 つの方法で使用して要素を結合するには、まず空の文字列を区切り文字として使用してリスト内のすべての要素を結合し、さらに次を使用してリストの要素を結合します。 $ 出力に見られるように区切り文字として使用されます。
パイソン # Joining with empty separator list1 = ['g', 'e', 'e', 'k', 's'] print(''.join(list1)) # Joining with string list1 = ' geeks ' print('$'.join(list1))> 出力:
geeks $g$e$e$k$s$>
Python でタプル要素を文字列に結合する
ここで、私たちは、 タプル Python を使用した要素の作成 参加する() このメソッドを使用すると、任意の文字を文字列に結合できます。
ソフトウェアのテストと種類パイソン
# elements in tuples list1 = ('1', '2', '3', '4') # put any character to join s = '-' # joins elements of list1 by '-' # and stores in string s s = s.join(list1) # join use to join a list of # strings to a separator s print(s)> 出力:
1-2-3-4>
Join join() メソッドを使用して要素を String に設定します
この例では、 パイソンセット 文字列を結合します。
注記: セットには一意の値のみが含まれるため、2 つの値のうち 4 4 が 1 つ印刷されます。
パイソン list1 = {'1', '2', '3', '4', '4'} # put any character to join s = '-#-' # joins elements of list1 by '-#-' # and stores in string s s = s.join(list1) # join use to join a list of # strings to a separator s print(s)> 出力:
1-#-3-#-2-#-4>
join() を使用して文字列を辞書に結合する
文字列を辞書で結合する場合、文字列は辞書のキーと結合します。 Python辞書 、値ではありません。
パイソン dic = {'Geek': 1, 'For': 2, 'Geeks': 3} # Joining special character with dictionary string = '_'.join(dic) print(string)> 出力:
'Geek_For_Geeks'>
注記: 辞書キーを結合すると、次のキーのみが結合されます。 弦 のみ 整数ではありません これをコードで見てみましょう。
Linuxファイルパイソン
dic = {1:'Geek', 2:'For', 3:'Geeks'} # Joining special character with dictionary string = '_'.join(dic) print(string)> 出力:
Hangup (SIGHUP) Traceback (most recent call last): File 'Solution.py', line 4, in string = '_'.join(dic) TypeError: sequence item 0: expected string, int found>
Join() を使用して文字列のリストをカスタム セパレータで結合する
この例では、単語を区切る区切り文字を指定しています。 リスト 最終結果を出力しています。
パイソン words = ['apple', '', 'banana', 'cherry', ''] separator = '@ ' result = separator.join(word for word in words if word) print(result)>
出力:
apple@ banana@ cherry>