Python での型キャスト (暗黙的および明示的) と例

型キャストは Python 変数を変換する方法です Python の暗黙的な型変換

  • Python の明示的な型変換
  • Python での暗黙的な型変換

    このメソッドでは、 パイソン データ型を別のデータ型に自動的に変換します。ユーザーはこのプロセスに関与する必要はありません。

    Python3




    # Python program to demonstrate> # implicit type Casting> # Python automatically converts> # a to int> a> => 7> print> (> type> (a))> # Python automatically converts> # b to float> b> => 3.0> print> (> type> (b))> # Python automatically converts> # c to float as it is a float addition> c> => a> +> b> print> (c)> print> (> type> (c))> # Python automatically converts> # d to float as it is a float multiplication> d> => a> *> b> print> (d)> print> (> type> (d))>

    出力:

      10.0  21.0 

    Python での明示的な型変換

    この方法では、Python は変数データ型を必要なデータ型に変換するためにユーザーの関与を必要とします。

    Python での型キャストの例

    主に、型キャストは次のデータ型関数を使用して実行できます。

    • Int(): Python Int() この関数は引数として float または string を受け取り、int 型のオブジェクトを返します。
    • 浮く(): パイソン 浮く() この関数は引数として int または string を取り、float 型のオブジェクトを返します。
    • str(): パイソン str() 関数は引数として float または int を受け取り、文字列型のオブジェクトを返します。

    Python の Int から Float への変換

    さあ、私たちは Python での Int から Float への変換 とともに 浮く() 関数。

    Python3




    # Python program to demonstrate> # type Casting> # int variable> a> => 5> # typecast to float> n> => float> (a)> print> (n)> print> (> type> (n))>

    出力:

    5.0 

    Python Float を Int に変換する

    さあ、私たちは 変換中 Python での Float から int データ型への変換 int() 関数。

    Python3




    # Python program to demonstrate> # type Casting> # int variable> a> => 5.9> # typecast to int> n> => int> (a)> print> (n)> print> (> type> (n))>

    出力:

    5 

    Python の int から String への変換

    さあ、私たちは 変換中 Python で int から String データ型へ str() 関数。

    Python3




    # Python program to demonstrate> # type Casting> # int variable> a> => 5> # typecast to str> n> => str> (a)> print> (n)> print> (> type> (n))>

    出力:

    5 

    Python 文字列を浮動小数点に変換する

    ここでは、文字列データ型を float データ型にキャストしています。 浮く() 関数。

    Python3




    # Python program to demonstrate> # type Casting> # string variable> a> => '5.9'> # typecast to float> n> => float> (a)> print> (n)> print> (> type> (n))>

    出力:

    5.9 

    Python 文字列を int に変換する

    さあ、私たちは 変換中 Python での文字列から int データ型への変換 int() 関数。指定された文字列が数値でない場合は、エラーがスローされます。

    Python3




    # string variable> a> => '5'> b> => 't'> # typecast to int> n> => int> (a)> print> (n)> print> (> type> (n))> print> (> int> (b))> print> (> type> (b))>

    出力:

    5  --------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[3], line 14  11 print(n)  12 print(type(n)) --->14 print(int(b)) 15 print(type(b)) ValueError: 基数 10 の int() のリテラルが無効です: 't' 

    明示的な変換を使用した文字列と整数の加算

    Python3




    # integer variable> a> => 5> # string variable> b> => 't'> # typecast to int> n> => a> +> b> print> (n)> print> (> type> (n))>

    出力:

    10 n = a+b 12 print(n) 13 print(type(n))>>