python如何判断变量是否是字符串
Python中的数据类型有数字、字符串,列表、元组、字典、集合等。
相关推荐:《Python教程》
python中,判断某变量的数据类型是否为字符串,可用isinstance()函数,也可通过比较type(x)==type(‘a’)的值来判断。
第一种方法:
第二种方法:
本回答由网友推荐
python字符串的判断
用正则表达式:
importre
ifre.match(r’.+\.vtx\[\d+\]’,’pTorus1.vtx[194]’)isnotNone:
print’yes’
能加个好友吗,python初学很晕
本回答由提问者推荐
我怎样才能判断一个Python变量是一个字符串或列表
python官方文档在说明type函数的用法时,明文推荐用isinstance测试对象类型。
isinstance似乎不是这么用的。 我通常的做法是用type
x=int(5)
if type(x)==int: print ” x is interger. “
else: print “false.”
isinstance可以用来判断一个变量是否属于一个类。 在python里应该是正确的。
if type(x)==list:pass
if type(x)==dict:passdef test(var):
try:
var+”1″
print(“{} is string”.format(var))
except TypeError:
print(“{} is not string”.format(var))
# do something as list
for x in var:
print(x)看能否跟字符串相连,用 try 处理,非常简洁。三个单引号Python 2.7.3 (default, Mar 14 2014, 11:57:14)
[GCC 4.7.2] on linux2
Type “help”, “copyright”, “credits” or “license” for more information.
>>> astr = “abcdefg”
>>> alst = list(astr)
>>> astr
‘abcdefg’
>>> alst
[‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’]
>>> isinstance(alst, list)
>>> isinstance(astr, list)
False
>>> isinstance(alst, str)
False
>>> isinstance(astr, str)
>>>type(变量)
会返回变量的类型
在程序里你可以这样来判断
if type(a) == type([]):
####import types
if type(a) == types.StringType:
# string
elif type(a) == types.ListType:
# list
python如何判断字符串包括字母和数字以及特殊符号?
你说的三类
>=’A'<=’Z’大写字母
>=’a'<=’z’小写字母
类似的 数字
其他的 就是 特殊符号可以考虑使用正则表达式来进行处理,搜一下python正则表达式的用法
文章出处登录后可见!