检查变量是否为字符串的Python程序
Python|检查变量是否为字符串
要检查定义的变量是否为字符串类型,我们可以使用两个函数,它们是Python库函数,
使用isinstance()
使用type()
1)使用isinstance()函数检查变量是否为字符串
isinstance()函数接受两个参数–1)变量名(对象)和2)数据类型(类),并返回对象是类的实例还是其子类的实例。
语法:
isinstance(obj, class_or_tuple)
示例
# 变数
a = 100 # 整数变量
b = 10.23 # 浮点变量
c = 'A' # 一个字符变量
d = 'Hello' # 字符串变量
e = "Hello" # 字符串变量
# 检查类型
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.")输出结果
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()函数检查变量是否为字符串
type()函数接受一个参数(其他参数是可选的),并返回其类型。
语法:
type(object)
示例
# 变数
a = 100 # 整数变量
b = 10.23 # 浮点变量
c = 'A' # 一个字符变量
d = 'Hello' # 字符串变量
e = "Hello" # 字符串变量
# 检查类型
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.")输出结果
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.
热门推荐
1 如何训练狗狗不叫
2 训练狗狗不叫
3 训练狗狗随行
4 怎么训练狗狗不叫
7 训练比熊狗狗教程
10 上海狗狗训练
11 怎么训练狗狗上厕所
12 训练狗狗趴下
13 狗狗服从训练
14 训练狗狗拒食
15 训练狗狗笑
16 训练狗狗大便
17 训练狗狗立
18 训练狗狗捡东西