
2.4 基本数据类型
知识链接
Python提供的基本数据类型主要有布尔类型、整型、浮点型、字符串、列表、元组、集合、字典等。
1.空(None)
表示该值是一个空对象,空值是Python里一个特殊的值,用None表示。None不能理解为0,因为0是有意义的,而None是一个特殊的空值。
2.布尔类型(Boolean)
在Python中,None、任何数值类型中的0、空字符串" "、空元组()、空列表[]、空字典{}都被当作False,还有自定义类型,如果实现了nonzero()或len()方法且方法返回0或False,则其实例也被当作False,其他对象均为True。布尔值和布尔代数的表示完全一致,一个布尔值只有True、False两种值,要么是True,要么是False,在Python中,可以直接用True、False表示布尔值(请注意大小写),也可以通过布尔运算计算出来。
3.整型(Int)
在Python内部对整数的处理分为普通整数和长整数,普通整数长度为机器位长,通常都是32位,超过这个范围的整数就自动当长整数处理,而长整数的范围几乎完全没限制,Python可以处理任意大小的整数,当然包括负整数,在程序中的表示方法和数学上的写法一模一样,如1、100、-8080、0等。
4.浮点型(Float)
Python的浮点数就是数学中的小数,类似C语言中的double。在运算中,整数与浮点数运算的结果是浮点数,浮点数也就是小数,之所以称为浮点数,是因为按照科学记数法表示时,一个浮点数的小数点位置是可变的,例如,1.23×109和12.3×108是相等的。浮点数可以用数学写法,如1.23、3.14、-9.01等。但是对于很大或很小的浮点数,就必须用科学计数法表示,把10用e替代,1.23×109就是1.23e9,或者12.3e8(也可以写成12.3e+8),0.000012可以写成1.2e-5,等等。
整数和浮点数在计算机内部存储的方式是不同的,整数运算永远是精确的(除法难道也是精确的?是的),而浮点数运算则可能会有四舍五入的误差。
5.字符串(String)
Python的字符串既可以用单引号(' '),也可以用双引号括起来(" "),甚至还可以用三引号(""" """)括起来,字符串是以"或" "括起来的任意文本,如'abc'、"xyz"等。请注意,"或" "本身只是一种表示方式,不是字符串的一部分,因此,字符串'abc'只有a、b、c这3个字符。如果' '(单引号)本身也是一个字符,那就可以用" "(双引号)括起来,如"I'm OK"包含的字符是I、'、m、空格、O、K这6个字符。如果字符串内部既包含' '又包含" "怎么办?可以用转义字符“\”来标识。
Python字符串的常用操作,如字符串的替换、删除、截取、赋值、连接、比较、查找、分割等,如表2.5所示。
表2.5 字符串操作汇总表

除了以上所述的基本数据类型之外,还有列表、元组、集合、字典等数据类型在第4章论述。
课堂任务
1.了解基本数据类型。
2.掌握数值型数据。
3.掌握字符串操作方案。
探究活动
任务1
创建字符串,可以通过双引号(" ")或者单引号(' ')来创建。

任务2
字符串的拼接,是指将str1和str2拼接成一个新的字符串str3,主要有两种方式。
方式1:用“+”号来拼接。
str3=str1+str2 print("这是str3:"+str3)
方式2:用join方法来链接两个字符串。
str4=','.join(str1) print(str4)
任务3
去掉空格和换行符(/r).strip()方法。

任务4
查看字符串是否都是字母或文字,并至少有一个字符。

课堂练习
1.创建字符串,可以通过双引号(" ")或者单引号(' ')来创建。

2.print()方法默认在打印完成后会换行,其实它有一个end参数,可以用end=""来去除换行。

3.print()方法在打印多行的字符时,默认是以一个空格来分隔的。我们可以使用sep来指定分隔的符号。

4.Python 3之后建议用.format()来格式化字符串。第一个括号接收的是1,第二个接收的是2,第三个接收的是(1+2)。

5.去掉某个字符串。

拓展训练
1.查找某个字符在字符串中出现的次数。
name="python学n习 -5" name_count=name.count('n') print('n出现了: ', name_count, end="次")
2.首字母大写。

3.把字符串放中间,两边用“-”补齐。

4.在字符串中找到目标字符的位置,有多个时返回第一个所在位置,找不到时返回-1。

5.字符串替换。

6.查看是否都是数字。

7.查看是否都是小写使用islower(),是否都是大写使用isupper()。

8.字符串分割。
