如何检查变量的类型是否为字符串? [英] How to check if type of a variable is string?

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

问题描述

有没有办法检查python中变量的类型是否为string,例如:

Is there a way to check if the type of a variable in python is a string, like:

isinstance(x,int);

对于整数值?

推荐答案

在 Python 2.x 中,你会这样做

In Python 2.x, you would do

isinstance(s, basestring)

basestring抽象超类strunicode.可以用来测试一个对象是str还是unicode的实例.

basestring is the abstract superclass of str and unicode. It can be used to test whether an object is an instance of str or unicode.

在 Python 3.x 中,正确的测试是

In Python 3.x, the correct test is

isinstance(s, str)

bytes 类在 Python 3 中不被视为字符串类型.

The bytes class isn't considered a string type in Python 3.

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

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