Python
 Computer >> コンピューター >  >> プログラミング >> Python

Pythonで変数がタプルかどうかを確認します


変数がタプルであるかどうかを確認する必要がある場合は、「type」メソッドを使用できます。タプルは不変のデータ型です。つまり、一度定義された値は、インデックス要素にアクセスして変更することはできません。要素を変更しようとすると、エラーが発生します。読み取り専用アクセスを保証するため、これらは重要な内容です。

'type'メソッドは、引数として渡されるiterable/valueのタイプを確認します。

以下は同じのデモンストレーションです-

my_tuple_1 = (7, 8, 0, 3, 45, 3, 2, 22, 4)

print ("The tuple is : " )
print(my_tuple_1)

my_result = type(my_tuple_1) is tuple

print("Is the given variable a tuple ? ")
print(my_result)

出力

The tuple is :
(7, 8, 0, 3, 45, 3, 2, 22, 4)
Is the given variable a tuple ?
True

説明

  • タプルが定義され、コンソールに表示されます。
  • タプルのタイプが調べられ、「is」および「tuple」演算子を使用して、タプルタイプであるかどうかがチェックされます。
  • この結果は値に割り当てられます。
  • コンソールに出力として表示されます。

  1. Pythonで変数の型が文字列であるかどうかを確認するにはどうすればよいですか?

    isinstance(var、class)を使用して、varが指定されたクラスのインスタンスであるかどうかを確認できます。 Python 2.xでは、strとunicodeの基本クラスはbasestringです。したがって、次のように使用できます。 >>> s = 'A string' >>> isinstance(s, basestring) True >>> isinstance(s, str) True >>> isinstance(10, basestring) False 注:Python

  2. Python変数が存在するかどうかを確認するにはどうすればよいですか?

    次のコードを使用して、Pythonに変数が存在するかどうかを確認します。 例 x =10 class foo: g = 'rt' def bar(self): m=6 print (locals()) if 'm' in locals(): print ('m is local variable') else: print ('m is not a local variable') f = foo() f.bar() print (globals()) if hasattr(f, 'g'): print ('