【Py】数据类型、变量类型查询

数据类型:

int:整型

  int()将数据以截取的方式转换成整数,如果想按四舍五入的方式转换可以采用以下代码:

1 >>> int(4.3+0.5)
2 4
3 >>> int(4.6+0.5)
4 5

 

float:浮点型,包括浮点型和科学计数法两种

  float()将数据转换成浮点型

str:字符串

  str()将数据转换成字符串型

bool:布尔函数

 

变量类型查询:

type()

1 >>> type('520')
2 <class 'str'>
3 >>> type(520)
4 <class 'int'>
5 >>> type(3e18)
6 <class 'float'>
7 >>> type(True)
8 <class 'bool'>

isinstance(),返回结果比较明显

1 >>> isinstance(520,int)
2 True
3 >>> isinstance('520',float)
4 False

判断输入字符串是否符合预想类型可以通过以下函数实现:

 1 #s为字符串
 2 s.isalnum()  #所有字符为数字或字母,为真返回Ture,否则返回False
 3 s.isalpha()   #所有字符为字母,为真返回Ture,否则返回False
 4 s.isdigit()    #所有字符为数字,为真返回Ture,否则返回False
 5 s.islower()   #所有字符为小写,为真返回Ture,否则返回False
 6 s.isupper()  #所有字符为大写,为真返回Ture,否则返回False
 7 s.istitle()     #所有字符为首字母大写,为真返回Ture,否则返回False
 8 s.isspace()  #所有字符为空白字符,为真返回Ture,否则返回False
 9 ======
10 >>> temp = 'Iloveyou'
11 >>> temp.isalnum()
12 True
13 ======
14 >>> temp = 'I love you'
15 >>> temp.isalnum()
16 False
 0 #判定给定年份是不是闰年
1
temp=input('请输入一个年份:') 2 while not temp.isdigit(): 3 temp=input('请重新输入:') 4 year = int(temp) 5 if year/400 == int(year/400): 6 print(temp+'是闰年') 7 else: 8 if (year/4 == int(year/4)) and (year/100 != int(year/100)): 9 print(temp+'是闰年') 10 else: 11 print(temp+'不是闰年')

 

posted @ 2016-03-05 16:43  喜闻乐见小逗逗  阅读(414)  评论(0编辑  收藏  举报