Python基本类型

来源:互联网 发布:娶网络女主播 编辑:程序博客网 时间:2024/06/05 23:03

1、数值型(Numbers)

x = 5print type(x)   #Prints "<type 'int'>"print x             #Prints "5"print x + 1       #Prints "6" 加减乘除和平常的一样print x**2       #Prints "25" 幂运算x += 1  #自加x *= 2  #自乘y = 2.5print type(y)  #Prints "<type 'float'>"

2、布尔型(Booleans)

t = Truef = Falseprint type(t)   #Prints "<type 'bool'>"print t and f   #Prints "False"print t or f   #Prints "True"print not t   #Prints "False"print t != f   #Prints "True"

3、字符串(String)

hello = 'hello'world = 'world'print helloprint len(hello)hw = hello + ' ' + world #字符串连接print hwhw2017 = '%s %s %d' % (hello,world,2017)
打印结果:


s = "hello"print s.capitalize() #首字母大写print s.upper() #全部大写print s.rjust(7) #以7为长度右对齐,左边不空格print s.center(7) #居中,左右补空格print s.replace('l','(ooo)') #字符串替换print '   world   '.strip()  #去首尾空格print len('   world   '.strip())
打印结果:


4、Python容器

(1)list

nums = range(5)print nums   print nums[2:4]   #下标从2到4-1的元素print nums[2:]    #小标从2到结尾的元素print nums[:2]    #从开头到下标为2-1的元素print nums[:]     #所有元素print nums[:-1] #-1代表倒数,也就是最后一个函数nums[2:4] = [8,9] #对子序列赋值print nums

打印结果:





(2)dictionary

原创粉丝点击