Python 蟒蛇3为什么是';字符串';不是str?

Python 蟒蛇3为什么是';字符串';不是str?,python,string,python-3.x,Python,String,Python 3.x,我需要这个小片段来输出“thisastring”(我需要myVar来满足条件is str) 但当我运行它时,它会不断输出“这不是字符串”。 我不明白,有人能指出我做错了什么以及如何纠正吗 我也试过: myVar = str('some-string') if myVar is str: print('this is a string') else: print('this is NOT a string') 而且它也不起作用 我不能使用isinstance()检查任何内容,我必

我需要这个小片段来输出“thisastring”(我需要myVar来满足条件is str)

但当我运行它时,它会不断输出“这不是字符串”。 我不明白,有人能指出我做错了什么以及如何纠正吗

我也试过:

myVar = str('some-string')
if myVar is str:
    print('this is a string')
else:
    print('this is NOT a string')
而且它也不起作用

我不能使用isinstance()检查任何内容,我必须保留

if myVar is str:
这个条件的值必须为True

我也试过:

if 'some-string' is str:
    print('this is a string')
else:
    print('this is NOT a string')
这也会输出“这不是字符串”


我不知道我需要做什么才能给它提供满足此条件的东西

您的检查不正确,
str
是类
类型的对象
,它可以创建
类str
的实例正确的检查是:

myVar = str('some-string')
if isinstance(myVar,str):
    print('this is a string')
else:
    print('this is NOT a string')
与本检查中给出的
A类
相同:

如果x是一个
不正确


定义一个类会创建一个class
类型的特殊对象
,该对象负责创建已定义类的实例,这就是为什么您需要使用
isinstace()
issubclass()
来使用此特殊对象和给定的对象来回答查询的原因。因为simple
is
检查对象x是否为对象A,而这不是真的。

如果要检查对象是否为字符串(或任何类型的字符串),请使用
isinstance(Myvar,str)
,如果Myvar为字符串,则为真

因此:

要成为pythonic,不要将大写字母用作变量…

有两种方法:

if type(myVar) is str:


查看以了解
是什么
的功能。“我不能使用isinstance()检查任何内容,我必须保留条件”这很不幸。如果你想让python解释器工作,你必须重写它。祝你好运。请将其中一个解决方案标记为正确。当我尝试你的代码时,它确实会输出“thisastring”,谢谢!我会努力纠正我的状况
myvar = 'this is a string'
if isinstance(myvar, str):
    print(f'the variable {myvar} is a string')
else:
    print(f'the variable {myvar} is not a string')
if type(myVar) is str:
if isinstance(myVar, str):
>>> string = "Hello"
>>> isinstance(string,str)
True
>>> isinstance(1,str)
False
>>> if isinstance(string,str):
    print("this is a string")
else:
    print("this is not a string")

this is a string
>>>