Pythonの文字列の結合

プログラミングにおいて、文字の連結は非常に一般的な操作です。Pythonでは、文字の連結はさまざまな方法で行うことができます。このチュートリアルでは、Pythonプログラムで文字列を連結するさまざまな方法を探求することを目的としています。

Pythonの文字列結合

以下の方法を使用して文字列の連結を行うことができます。

  • Using + operator
  • Using join() method
  • Using % operator
  • Using format() function
  • Using f-string (Literal String Interpolation)

「+ 演算子を使用して文字列を連結する」

これは文字列の連結の最も簡単な方法です。簡単な例を見てみましょう。

s1 = 'Apple'
s2 = 'Pie'
s3 = 'Sauce'

s4 = s1 + s2 + s3

print(s4)

出力:ApplePieSauce 別の例を見てみましょう。ここでは、ユーザーの入力から2つの文字列を取得して連結します。

s1 = input('Please enter the first string:\n')
s2 = input('Please enter the second string:\n')

print('Concatenated String =', s1 + s2)

出力:

Please enter the first string:
Hello
Please enter the second string:
World
Concatenated String = HelloWorld
python string concatenation
>>>'Hello' + 4
Traceback (most recent call last):
  File "<input>", line 1, in 
TypeError: can only concatenate str (not "int") to str

オブジェクトの文字列表現を取得するために、str()関数を使用することができます。文字列を整数や別のオブジェクトに連結する方法を見てみましょう。

print('Hello' + str(4))


class Data:
    id = 0

    def __init__(self, i):
        self.id = i

    def __str__(self):
        return 'Data[' + str(self.id) + ']'


print('Hello ' + str(Data(10)))

出力:

Hello4
Hello Data[10]

+演算子の最も大きな問題は、文字列の間にセパレータやデリミタを追加できないことです。例えば、「Hello」と「World」を空白のセパレータで連結する場合、”Hello” + ” ” + “World” と書かなければなりません。

join()関数を使用した文字列の連結

join()関数を使用すると、セパレータで文字列を連結することができます。これは、例えば文字列のリストやタプルなどのシーケンスがある場合に便利です。セパレータを必要としない場合は、空の文字列を使用してjoin()関数を使います。

s1 = 'Hello'
s2 = 'World'

print('Concatenated String using join() =', "".join([s1, s2]))

print('Concatenated String using join() and whitespaces =', " ".join([s1, s2]))

出力:

Concatenated String using join() = HelloWorld
Concatenated String using join() and spaces = Hello World

%演算子を使用した文字列の連結

文字列フォーマットには%演算子を使うことができます。また、文字列の連結にも使用することができます。文字列を連結したり、簡単なフォーマットを行いたい場合に便利です。

s1 = 'Hello'
s2 = 'World'

s3 = "%s %s" % (s1, s2)
print('String Concatenation using % Operator =', s3)

s3 = "%s %s from JournalDev - %d" % (s1, s2, 2018)
print('String Concatenation using % Operator with Formatting =', s3)

出力:

String Concatenation using % Operator = Hello World
String Concatenation using % Operator with Formatting = Hello World from JournalDev - 2018

format()関数を使用して、文字列の連結を行います。

string concatenationとフォーマットには、string format()関数を使用することができます。

s1 = 'Hello'
s2 = 'World'

s3 = "{}-{}".format(s1, s2)
print('String Concatenation using format() =', s3)

s3 = "{in1} {in2}".format(in1=s1, in2=s2)
print('String Concatenation using format() =', s3)

結果:

String Concatenation using format() = Hello-World
String Concatenation using format() = Hello World

PythonのString format()関数は非常に強力であり、単純に文字列の連結に使用することは適切ではありません。

f-stringを使用して文字列の結合

Python 3.6以降を使用している場合、文字列の連結にはf文字列を使用することもできます。これは文字列をフォーマットする新しい方法であり、PEP 498 – リテラル文字列インターポレーションで導入されました。

s1 = 'Hello'
s2 = 'World'

s3 = f'{s1} {s2}'
print('String Concatenation using f-string =', s3)

name = 'Pankaj'
age = 34
d = Data(10)

print(f'{name} age is {age} and d={d}')

出力:

String Concatenation using f-string = Hello World
Pankaj age is 34 and d=Data[10]

Pythonのf-文字列は、format()関数と比べて書くのが簡潔で容易です。また、オブジェクト引数をフィールドの置換として使用する場合には、str()関数を呼び出します。

結論

Pythonの文字列のフォーマットは、いくつかの方法で行うことができます。必要に応じてそれらを使用してください。文字列のシーケンスを区切り記号で連結する必要がある場合は、join()関数を使用します。連結とともにフォーマットも必要な場合は、format()関数またはf-stringを使用します。ただし、f-stringはPython 3.6以上のバージョンで使用できます。

私たちのGitHubリポジトリからは、Pythonの完全なスクリプトやその他のPythonの例をチェックアウトすることができます。

コメントを残す 0

Your email address will not be published. Required fields are marked *