Pythonの文字列に追加する

Pythonの文字列オブジェクトは不変です。そのため、2つの文字列を連結するために+演算子を使用するたびに新しい文字列が作成されます。多くの文字列を追加する場合は、最終的な結果を得る前に不必要に多くの一時的な文字列が作成されるので、+演算子を使用する必要はありません。

Pythonの文字列に追加する

「n」回、文字列を連結する関数を見てみましょう。

def str_append(s, n):
    output = ''
    i = 0
    while i < n:
        output += s
        i = i + 1
    return output

以下の関数は、+演算子の使用方法を示すために定義しています。後でtimeitモジュールを使用してパフォーマンスをテストします。文字列を単純に「n」回連結するだけなら、s = ‘Hi’ * 10 と簡単にできますので、ご注意ください。

文字列の追加操作の別の方法は、リストを作成し、文字列をリストに追加することです。そして、それらをマージして結果の文字列を得るために、文字列のjoin() 関数を使用します。

def str_append_list_join(s, n):
    l1 = []
    i = 0
    while i < n:
        l1.append(s)
        i += 1
    return ''.join(l1)

予想通りに機能しているか確認するために、これらの方法をテストしましょう。 (Yosōdōri ni kinō shite iru ka kakunin suru tame ni, korera no hōhō o tesuto shimashou.)

if __name__ == "__main__":
    print('Append using + operator:', str_append('Hi', 10))
    print('Append using list and join():', str_append_list_join('Hi', 10))
    # use below for this case, above methods are created so that we can
    # check performance using timeit module
    print('Append using * operator:', 'Hi' * 10)

アウトプット: 日本語での適切な表現のみが必要です。

Append using + operator: HiHiHiHiHiHiHiHiHiHi
Append using list and join(): HiHiHiHiHiHiHiHiHiHi
Append using * operator: HiHiHiHiHiHiHiHiHiHi

Pythonで文字列を追加する最良の方法は何ですか。

私は、string_append.pyファイルで定義された両方のメソッドを持っています。そのパフォーマンスをチェックするために、timeitモジュールを使用しましょう。

$ python3.7 -m timeit --number 1000 --unit usec 'import string_append' 'string_append.str_append("Hello", 1000)' 
1000 loops, best of 5: 174 usec per loop
$ python3.7 -m timeit --number 1000 --unit usec 'import string_append' 'string_append.str_append_list_join("Hello", 1000)'
1000 loops, best of 5: 140 usec per loop

$ python3.7 -m timeit --number 1000 --unit usec 'import string_append' 'string_append.str_append("Hi", 1000)' 
1000 loops, best of 5: 165 usec per loop
$ python3.7 -m timeit --number 1000 --unit usec 'import string_append' 'string_append.str_append_list_join("Hi", 1000)'
1000 loops, best of 5: 139 usec per loop
python string append, python add to string

要約: This requires a native speaker to translate it.

もし文字列が少ない場合は、任意の方法で文字列を追加することができます。可読性の観点からは、+演算子を使用する方が少ない文字列では良いように思われます。しかし、大量の文字列を追加する必要がある場合は、リストとjoin()関数を使用するべきです。

私たちのGitHubリポジトリから、完全なPythonスクリプトやさらに多くのPythonの例をチェックアウトできます。

コメントを残す 0

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