如何检查变量是否是与 python 2 和 3 兼容的字符串 [英] How to check if variable is string with python 2 and 3 compatibility

查看:44
本文介绍了如何检查变量是否是与 python 2 和 3 兼容的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以在 python-3.x 中使用: isinstance(x, str) 但我需要检查某些东西是否也是 python-2.x 中的字符串.isinstance(x, str) 会在 python-2.x 中按预期工作吗?还是我需要检查版本并使用 isinstance(x, basestr)?

I'm aware that I can use: isinstance(x, str) in python-3.x but I need to check if something is a string in python-2.x as well. Will isinstance(x, str) work as expected in python-2.x? Or will I need to check the version and use isinstance(x, basestr)?

具体来说,在 python-2.x 中:

Specifically, in python-2.x:

>>>isinstance(u"test", str)
False

和 python-3.x 没有 u"foo"

and python-3.x does not have u"foo"

推荐答案

如果您正在编写 2.x 和 3.x 兼容的代码,您可能想要使用 六个:

If you're writing 2.x-and-3.x-compatible code, you'll probably want to use six:

from six import string_types
isinstance(s, string_types)

这篇关于如何检查变量是否是与 python 2 和 3 兼容的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆