在Python中检查一个变量是否是一个字符串

117 阅读1分钟

在本教程中,我们将在实例的帮助下学习如何在Python中检查一个变量是否是字符串。

考虑一下,我们的代码中有以下变量。

name = "olive"

现在,我们需要检查上述变量是否是一个字符串。

使用type()函数

为了检查一个变量是否是字符串,我们可以使用Python中内置的type() 函数。

type() 函数将变量作为一个参数,并返回下面对象的类型。

下面是一个例子。

name = "olive"

if type(name) == str:
    print('Variable is a string')
else:
    print('Variable is not a string')

输出。

'Variable is a string'

在上面的代码中。

  1. 我们首先用一个字符串初始化了这个变量。

  2. 然后我们用平等== 操作符来检查两个值是否指的是同一个对象。

如果返回True ,那么就打印出variable is a string ,如果变量不是字符串,那么就返回False ,并打印出Variable is not a string

另一个例子。

age = 23

if type(age) == str:
    print('Variable is string')
else:
    print('Variable is not a string')

输出。

'Variable is not a string'

我们也可以使用is ,而不是平等运算符,像这样。

age = 23

if type(age) is str:
    print('Variable is string')
else:
    print('Variable is not a string')

使用isinstance()函数

另外,我们也可以使用Python中的isinstance() 函数来检查一个给定的变量是否是字符串。

isinstance() 函数接收两个参数,第一个参数是object ,第二个参数是type ,然后如果一个给定的对象是指定的类型,它返回True ,否则它返回 False 。

name = "olive"

if  isinstance(name, str):
    print('Variable is a string')
else:
    print('Variable is not a string')