python 字符串 變量
Python | 檢查變量是否為字符串 (Python | Check if a variable is a string)
To check whether a defined variable is a string type or not, we can use two functions which are Python library functions,
要檢查定義的變量是否為字符串類型,我們可以使用兩個函數,它們是Python庫函數,
Using isinstance()
使用isinstance()
Using type()
使用type()
1)使用isinstance()函數檢查變量是否為字符串 (1) Checking a variable is a string or not using isinstance() function)
isinstance() function accepts two parameters – 1) variable name (object) and 2) data type (class) and returns whether an object is an instance of a class or of a subclass thereof.
isinstance()函數接受兩個參數– 1)變量名( 對象 )和2)數據類型( 類 ),并返回對象是類的實例還是其子類的實例。
Syntax:
句法:
isinstance(obj, class_or_tuple)
Example:
例:
# variables
a = 100 # an integer variable
b = 10.23 # a float variable
c = 'A' # a character variable
d = 'Hello' # a string variable
e = "Hello" # a string variable
# checking types
if isinstance(a, str):
print("Variable \'a\' is a type of string.")
else:
print("Variable \'a\' is not a type of string.")
if isinstance(b, str):
print("Variable \'b\' is a type of string.")
else:
print("Variable \'b\' is not a type of string.")
if isinstance(c, str):
print("Variable \'c\' is a type of string.")
else:
print("Variable \'c\' is not a type of string.")
if isinstance(d, str):
print("Variable \'d\' is a type of string.")
else:
print("Variable \'d\' is not a type of string.")
if isinstance(e, str):
print("Variable \'e\' is a type of string.")
else:
print("Variable \'e\' is not a type of string.")
Output
輸出量
Variable 'a' is not a type of string.
Variable 'b' is not a type of string.
Variable 'c' is a type of string.
Variable 'd' is a type of string.
Variable 'e' is a type of string.
2)使用type()函數檢查變量是否為字符串 (2) Checking a variable is string using type() function)
type() function accepts one parameter (others are optional), and returns its type.
type()函數接受一個參數(其他參數是可選的),并返回其類型。
Syntax:
句法:
type(object)
Example:
例:
# variables
a = 100 # an integer variable
b = 10.23 # a float variable
c = 'A' # a character variable
d = 'Hello' # a string variable
e = "Hello" # a string variable
# checking types
if type(a) == str:
print("Variable \'a\' is a type of string.")
else:
print("Variable \'a\' is not a type of string.")
if type(b) == str:
print("Variable \'b\' is a type of string.")
else:
print("Variable \'b\' is not a type of string.")
if type(c) == str:
print("Variable \'c\' is a type of string.")
else:
print("Variable \'c\' is not a type of string.")
if type(d) == str:
print("Variable \'d\' is a type of string.")
else:
print("Variable \'d\' is not a type of string.")
if type(e) == str:
print("Variable \'e\' is a type of string.")
else:
print("Variable \'e\' is not a type of string.")
Output
輸出量
Variable 'a' is not a type of string.
Variable 'b' is not a type of string.
Variable 'c' is a type of string.
Variable 'd' is a type of string.
Variable 'e' is a type of string.
翻譯自: https://www.includehelp.com/python/check-whether-a-variable-is-a-string-or-not.aspx
python 字符串 變量