Python で変数が文字列かどうかを確認する

Rana Hasnain Khan 2024年2月15日
Python で変数が文字列かどうかを確認する

Python で変数が文字列かどうかを確認する 2つの異なる方法を例を挙げて紹介します。

Python で変数が文字列かどうかを確認する

Python では、すべての変数にデータ型があります。 データ型は、変数が内部に格納しているデータの種類を表します。

データ型は、string、int、float など、格納できるさまざまなデータ型を区別するためのプログラミング言語の最も重要な機能です。

多くのプログラミングの問題に取り組んでいると、特定の変数に対していくつかのタスクを実行するためにそのデータ型を見つける必要があるという問題に遭遇する場合があります。

Python には、任意の変数のデータ型を取得するために使用される 2つの関数 isinstance()type() が用意されています。 変数が特定のデータ型を確実に格納するようにしたい場合は、isinstance() 関数を使用できます。

2つの変数を作成する例を見てみましょう。1つはデータ型が string で、もう 1つはデータ型が int です。 両方の変数をテストし、isinstance() 関数がデータ型を検出できるかどうかを確認します。

コード例:

# python
testVar1 = "This is a string"
testVar2 = 13

if isinstance(testVar1, str):
    print("testVar1 is a string")
else:
    print("testVar1 is not a string")

if isinstance(testVar2, str):
    print("testVar2 is a string")
else:
    print("testVar2 is not a string")

出力:

Python で isinstance メソッドを使用して変数をテスト

出力からわかるように、関数は変数のデータ型を正確に検出できます。

2 番目の関数 type() で同じシナリオを試してください。

コード例:

# python
testVar1 = "This is a string"
testVar2 = 13

if type(testVar1) == str:
    print("testVar1 is a string")
else:
    print("testVar1 is not a string")

if type(testVar2) == str:
    print("testVar2 is a string")
else:
    print("testVar2 is not a string")

出力:

Python で型メソッドを使用して変数をテスト

type() を使用して、任意の変数のデータ型を検出し、それに応じて関数を実行できます。

Rana Hasnain Khan avatar Rana Hasnain Khan avatar

Rana is a computer science graduate passionate about helping people to build and diagnose scalable web application problems and problems developers face across the full-stack.

LinkedIn