import sysPY2 = sys.version_info.major == 2
# Check if string (lenient for byte-strings on Py2):isinstance('abc', basestring if PY2 else str)
# Check if strictly a string (unicode-string):isinstance('abc', unicode if PY2 else str)
# Check if either string (unicode-string) or byte-string:isinstance('abc', basestring if PY2 else (str, bytes))
# Check for byte-string (Py3 and Py2.7):isinstance('abc', bytes)
我不知道为什么在我面前没有一个答案包含这个简单的type(my_variable) is str语法,但是像这样使用type()对我来说似乎是最合乎逻辑和最简单的,到目前为止:
(在Python3中测试):
# Option 1: check to see if `my_variable` is of type `str`type(my_variable) is str
# Option 2: check to see if `my_variable` is of type `str`, including# being a subclass of type `str` (ie: also see if `my_variable` is any object# which inherits from `str` as a parent class)isinstance(my_variable, str)