本节主要记录了:数据类型的种类、列表的切片、字符串的操作以及字典的使用,并写了一个简单的购物车小程序。
数据类型
Python中有五个标准的数据类型:
- Numbers(数字)
- String(字符串)
- List(列表)
- Tuple(元组)
- Sets(集合)
- Dictionary(字典)
其中,列表、元组、以及字典属于集合类型。
不可变数据类型(四个):Number(数字)、String(字符串)、Tuple(元组)、Sets(集合);
可变数据(两个):List(列表)、Dictionary(字典)
Numbers(数字)
数字类型用于存储数值,是不可改变的数据类型。
有四种不同的数字类型:
- int (有符号整型)
- float (浮点型)
- bool (布尔型)
- complex (复数)
Python 3 中没有长整型,整数类型均可用int来表示;
a = 10
b = 1.5
c = True
d = 2+3j
print(type(a), type(b), type(c), type(d))
Python中常用的数值运算:
- +: 加法
- -: 减法
- *: 乘法
- /: 除法
- //: 除法(结果取整数)
- %: 取余
- **: 乘方
String(字符串)
- python中字符串使用单引号(”)或双引号(”“)括起来,使用反斜杠(\)转义特殊字符。
- 字符串的截取方法:变量[头下标:尾下标]
- 索引值从0开始,-1位末尾开始的位置
- 加号(+)可连接字符串,星号(*)可复制当前字符串。
字符串不可修改,即使做出的修改,也是覆盖掉了原字符串的修改;
字符串的常用操作
hello = "hello world!"
print(hello.capitalize())
>> Hello world!
print(hello.count("o")) #字符串中有多少个o
>> 2
print(hello.center(50,"-")) #一共打印50个字符,字符串放在中间,其余打印-
>> -------------------hello world!-------------------
print(hello.endswith("ld!")) #判断是否以"ld!"结尾
>> True
list = "hello \tworld" #加入\t(TAB键)
print(list.expandtabs(tabsize = 30)) #将字符串中的TAB键转成30个空格
>> hello world
print(hello.find("hello")) #寻找hello的索引位置
#可用于字符串的切片,例如:
print(hello[hello.find("world"):]) #即可从world开始打印到末尾
>> world!
#format的使用:
introduce = "my name is {name} and I am {year} years old"
print(introduce.format(name = "Evan",year = "22"))
>> my name is Evan and I am 22 years old
#使用字典方法:
print(introduce.format_map({
'name':'Evan','year':22}))
>>结果同上
isalnum:
print("ab33".isalnum()) #检测字符串是否仅包含字母和数字(不包括空格)
>> True
isidentifier:
print('1d'.isidentifier()) #判断是不是一个合法的标识符
istitle:
print('My name is...'.istitle()) #首字母是否大写
join:
print('+'.join(['1','2','3'])) #把+插入到1、2、3之间
>> 1+2+3
ljust:
print(hello.ljust(50,'*')) #打印字符串,长度50,不够就用*补上
>>