logo

Pythonで整数を文字列に変換する

Python では、組み込み関数を使用して整数を文字列に変換できます。 str() 関数。 str() 関数は、任意の値を受け取ります。 str() そうする唯一の方法ではありません。このタイプの変換は、 %s キーワード、 。フォーマット 関数または使用法 Fストリング 関数。

以下は、Python で整数を文字列に変換する可能な方法のリストです。

1. str()関数の使用



構文: str(整数値)

例:

Python3




num>=> 10> # check and print type of num variable> print>(>'Type of variable before conversion : '>,>type>(num))> # convert the num into string> converted_num>=> str>(num)> # check and print type converted_num variable> print>(>'Type After conversion : '>,>type>(converted_num))>

>

>

出力:

Type of variable before conversion : Type After conversion :>

2. %s キーワードを使用する

構文: %s % 整数

例:

Python3




num>=> 10> # check and print type of num variable> print>(>'Type of variable before conversion : '>,>type>(num))> # convert the num into string and print> converted_num>=> '% s'> %> num> print>(>'Type after conversion : '>,>type>(converted_num))>

>

>

出力:

Type of variable before conversion : Type after conversion :>

3. .format() 関数の使用

構文: 「{}」.format(整数)

例:

Python3




num>=> 10> # check and print type of num variable> print>(>'Type before conversion : '>,>type>(num))> # convert the num into string and print> converted_num>=> '{}'>.>format>(num)> print>(>'Type after conversion :'>,>type>(converted_num))>

>

>

出力:

Type before conversion : Type after conversion :>

4. f-stringの使用

構文: f'{整数}'

例:

Python3




num>=> 10> # check and print type of num variable> print>(>'Type before conversion : '>,>type>(num))> # convert the num into string> converted_num>=> f>'{num}'> # print type of converted_num> print>(>'Type after conversion : '>,>type>(converted_num))>

>

>

出力:

Type before conversion : Type after conversion :>

5. __str__() メソッドの使用

構文: I 整数.__str__()

Python3




num>=> 10> # check and print type of num variable> print>(>'Type before conversion : '>,>type>(num))> # convert the num into string> converted_num>=> num.__str__()> # print type of converted_num> print>(>'Type after conversion : '>,>type>(converted_num))>

>

>

出力:

Type before conversion : Type after conversion :>

6. str.isdigit() の使用

Python3


区切り文字を設定するJava



str_value>=> '1234'> if> str_value.isdigit():> >int_value>=> int>(str_value)> >print>(int_value)> >print>(>type>(int_value))> else>:> >raise> ValueError(>'Invalid literal for int(): {}'>.>format>(str_value))>

>

>

出力

1234>

7.join() メソッドの使用:

join() メソッドは、整数のリストを文字列に変換するために使用されます。 list() 関数を使用して整数を文字のリストに変換し、join() メソッドを使用してそれらを結合します。

Python3




num>=> 10> # check and print type of num variable> print>(>'Type before conversion : '>,>type>(num))> # convert the num into string> converted_num>=> ''.join(>list>(>str>(num)))> # print type of converted_num> print>(>'Type after conversion : '>,>type>(converted_num))>

>

>

出力

Type before conversion : Type after conversion :>

時間計算量: O(N) ここで、n は整数の桁数です。

空間の複雑さ:O(N) として n 個の要素を持つ文字のリストを作成する必要があります。