Day2

本节内容

  1. 列表、元组操作
  2. 字符串操作
  3. 字典操作
  4. 集合操作
  5. 文件操作
  6. 字符编码与转码
  7. 内置函数

 1、数据类型

Python3 中的数据类型:

  • Number(数字)
  • String(字符串)
  • List(列表)
  • Tuple(元组)
  • Sets(集合)
  • Dictionary(字典)

2、数字

Python3 支持 int、float、bool、complex(复数)

在Python 3里,只有一种整数类型 int,表示为长整型,没有 python2 中的 Long。

像大多数语言一样,数值类型的赋值和计算都是很直观的。

内置的type()函数可以用来查询变量所指的对象类型。

数字类型

A = 18         #整数 int
B = 3.1        #浮点 float
C = True      #布尔 bool
D = 7+3j       #复数 complex
print(type(A),"
", type(B), "
",type(C), "
",type(D))
View Code

 

数值运算

#数值运算
print (13+17)       #加法
print (888-666)     #减法
print (37 * 47)     #乘法
print (3/4)         #除法,得到一个浮点数
print (3//4)        #整除,得到一个整数
print (22%3)        #取余
print (3**2)        #乘方
View Code

  

注意:

  • 1、Python可以同时为多个变量赋值,如x, y = 1, 2。
  • 2、数字运算的优先级是先乘除后加减,可以通过()来改变运算顺序。例如  print ((2+3)*3)。
  • 3、数值的除法(/)总是返回一个浮点数,要获取整数使用//操作符。
  • 4、在混合计算时,Python会把整型转换成为浮点数。

3、字符串

Python中的字符串用单引号(')或双引号(")括起来,同时使用反斜杠()转义特殊字符。

str1 = 'wo ai bei jing tian an men'
str2 = "freedom"
str3 = "123"
print (type(str1),'
',type(str2),'
',type(str3))
View Code

查找元素位置

str1 = 'wo ai bei jing tian an men'
print(str1.find('ai'))
print(str1.find('i'))
print(str1.find('i',0,-1))
print(str1.find('i',0,1))
View Code

去除空白

#去空格示例
username = input('pls input username:')
if username == 'francis':
    print('welcome to oldboy')
#改进版
username = input('pls input username:')
if username.strip() == 'francis':
    print('welcome to oldboy')
View Code

统计长度

#统计长度
str1 = 'wo ai bei jing tian an men'
print(len(str1))
View Code

4、 列表、元组操作

List(列表) 是 Python 中使用最频繁的数据类型。是一个有序的数据集合,通过列表可以对数据实现最方便的存储、增删改查等操作

列表中元素的类型可以不相同,它支持数字,字符串甚至可以包含列表(嵌套)。

列表是写在方括号([])之间、用逗号分隔开的元素列表。

和字符串一样,列表同样可以被索引和截取,列表被截取后返回一个包含所需元素的新列表。

列表截取的语法格式如下:

变量[头下标:尾下标]

索引值以 0 为开始值,-1 为从末尾的开始位置。

取值(查看)/切片:

#认识有序的列表
names = ["xiao4","feng jie","francis","ben ber ba","ba ber ben"]   #定义一个列表,列表可以是空,names = []
print (names)
print (names[1])
print (names[0])                    #索引值以0为起始值
print (names[4])
print (names[-1])                   #-1为从末尾的起始位置
View Code

 取多个值:

#切片之后还是一个列表
print (names[1:4])                  #顾头不顾尾
print (names[0:-1])
print (names[0:])
print (names[:])
#可以设定步长
print (names[0:4:2])
print (names[::2])
View Code

追加:

#追加
# names.append("小鲜肉")
# print(names)
# names.append("小兵张嘎","张飞")
# print(names)
View Code

插入:

#插入
names.insert(0,"令狐冲")
names.insert(3,"小龙女")
print(names)
View Code

修改:

#修改
names[0] = "令狐撞"
print (names)
View Code

删除:

#删除
names.remove("令狐撞")
print(names)
del names[0]
print(names)
View Code

合并:

#合并
ip_list = ["192.168.1.1","10.1.2.4"]
new_list = names + ip_list
print (new_list)

new_list.extend(names)
print (new_list)
View Code

排序/倒序:

#排序
listA = ["xiao4","feng jie","francis","ben ber ba","ba ber ben","123","ABC","令狐冲"]
print(sorted(listA))
View Code

包含:

# 包含
listA = ["xiao4","feng jie","francis","ben ber ba","ba ber ben","123","ABC","令狐冲"]
print ('123' in listA)
View Code

遍历:

#遍历
listA = ["xiao4","feng jie","francis","ben ber ba","ba ber ben","123","ABC","令狐冲"]
for item in listA:
    print(item)
View Code

注意:

  • 1、List写在方括号之间,元素用逗号隔开。
  • 2、和字符串一样,list可以被索引和切片。
  • 3、列表截取的语法格式为:变量 [头下标:尾下标] 例如 names[0:-1] ,范围取值的时候顾头不顾尾
  • 4、列表有很多的方法可以调用,调用方法为"变量名." 例如 names.insert()
  • 4、理解列表怎么用和什么时候用很重要

元组

元组其实跟列表差不多,也是存一组数,只不是它一旦创建,便不能再修改,所以又叫只读列表

语法

1
names = ("alex","jack","eric")

它只有2个方法,一个是count,一个是index,完毕。  

程序练习 

请闭眼写出以下程序。

程序:购物车程序

需求:

  1. 启动程序后,让用户输入工资,然后打印商品列表
  2. 允许用户根据商品编号购买商品
  3. 用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒 
  4. 可随时退出,退出时,打印已购买商品和余额

2. 字符串操作    

 一些蛋疼的语法

3. 字典操作

字典(Dictionary) 是 Python 的内置数据类型之一,它定义了键和值之间一对一的关系,是以无序的方式储存的。

列表是有序的元素结合,字典是无序的元素集合。两者之间的区别在于:字典当中的元素是通过键来存取的,而不是通过偏移存取。

字典是一种映射类型,字典用"{ }"标识,它是一个无序的键(key) : 值(value)对集合。

在同一个字典中,键(key)必须是唯一的;键(key)必须使用不可变类型

创建一个字典:

1 #定义一个字典
2 dict1 = {
3     'stu1101': "项羽",
4     'stu1102': "刘邦",
5     'stu1103': "流氓",
6 }
7 print(dict1)
8 #也可以定义一个空字典
9 dict2 = {}
View Code

常见应用场景:

1、用户名密码

2、通讯录(手机/邮箱)

查看:

 1 #根据key取value的值
 2 dict1 = {
 3     'Alex': "18612345678",
 4     'Francis': "18913245678",
 5     'Wu sir': "18811112222",
 6 }
 7 # print(dict1['Alex'])    #方法1
 8 # print(dict1.get('Francis')) #方法2
 9 # print[dict1["liubang"]]   #方法1,如果key 不存在,报错
10 # print(dict1.get("liubang")) #方法2,如果key不存在,不报错,返回None
11 #查看key在不在字典里
12 print('Alex' in dict1)
13 #遍历所有key和value
14 for k in dict1.keys():
15     print(k)
16 for v in dict1.values():
17     print(v)
View Code

修改:

1 #修改key 对应的value
2 dict3 = {
3     'user1': "password1",
4     'user2': "password2",
5     'user3': "password3",
6 }
7 dict3['user1'] = 'PASSWORD1'
8 print(dict3['user1'])
View Code

新增:

1 #新增
2 dict4 = {
3     'user1': "password1",
4     'user2': "password2",
5     'user3': "password3",
6 }
7 dict4['user4'] = "password4"
8 print(dict4)
View Code

删除:

 1 #删除
 2 dict5 = {
 3     'user1': "password1",
 4     'user2': "password2",
 5     'user3': "password3",
 6 }
 7 
 8 dict5.pop('user1')
 9 print(dict5)
10 del dict5['user3']
11 print(dict5)
12 dict5.clear()
13 print(dict5)
View Code

补充:

多级字典嵌套及操作

 View Code
 View Code

循环dict 

复制代码
#方法1
for key in info:
    print(key,info[key])

#方法2
for k,v in info.items(): #会先把dict转成list,数据里大时莫用
    print(k,v)
复制代码

程序练习

程序: 三级菜单

要求: 

  1. 打印省、市、县三级菜单
  2. 可返回上一级
  3. 可随时退出程序

4.集合操作

集合是一个无序的,不重复的数据组合,它的主要作用如下:

  • 去重,把一个列表变成集合,就自动去重了
  • 关系测试,测试两组数据之前的交集、差集、并集等关系

常用操作

 View Code

5. 文件操作

对文件操作流程

1、打开文件

 1 #打开文件
 2 # f = open('file','r') #只读模式(默认)
 3 # f = open('file','w') #只写模式,先清空文件
 4 # f = open('file','x') #python3 新增的模式,如果文件存在,则报错,不存在,则只写
 5 # f = open('file','a') #追加模式
 6 # f = open('file','r+') #读写模式(常用)
 7 
 8 #ex1:打开一个文件
 9 f = open('file1','r')
10 data = f.read()
11 print(data)
12 f.close()
View Code

 

2、操作文件

 1 class file(object):
 2 
 3     def read(self, size=None): # real signature unknown; restored from __doc__
 4         读取指定字节数据
 5         """
 6         read([size]) -> read at most size bytes, returned as a string.
 7          
 8         If the size argument is negative or omitted, read until EOF is reached.
 9         Notice that when in non-blocking mode, less data than what was requested
10         may be returned, even if no size parameter was given.
11         """
12         pass
13  
14 
15     def readline(self, size=None): # real signature unknown; restored from __doc__
16         仅读取一行数据
17         """
18         readline([size]) -> next line from the file, as a string.
19          
20         Retain newline.  A non-negative size argument limits the maximum
21         number of bytes to return (an incomplete line may be returned then).
22         Return an empty string at EOF.
23         """
24         pass
25  
26     def readlines(self, size=None): # real signature unknown; restored from __doc__
27         读取所有数据,并根据换行保存值列表
28         """
29         readlines([size]) -> list of strings, each a line from the file.
30          
31         Call readline() repeatedly and return a list of the lines so read.
32         The optional size argument, if given, is an approximate bound on the
33         total number of bytes in the lines returned.
34         """
35         return []
36  
37     def seek(self, offset, whence=None): # real signature unknown; restored from __doc__
38         指定文件中指针位置
39         """
40         seek(offset[, whence]) -> None.  Move to new file position.
41          
42         Argument offset is a byte count.  Optional argument whence defaults to
43         0 (offset from start of file, offset should be >= 0); other values are 1
44         (move relative to current position, positive or negative), and 2 (move
45         relative to end of file, usually negative, although many platforms allow
46         seeking beyond the end of a file).  If the file is opened in text mode,
47         only offsets returned by tell() are legal.  Use of other offsets causes
48         undefined behavior.
49         Note that not all file objects are seekable.
50         """
51         pass
52  
53     def tell(self): # real signature unknown; restored from __doc__
54         获取当前指针位置
55         """ tell() -> current file position, an integer (may be a long integer). """
56         pass
57  
58     def write(self, p_str): # real signature unknown; restored from __doc__
59         写内容
60         """
61         write(str) -> None.  Write string str to file.
62          
63         Note that due to buffering, flush() or close() may be needed before
64         the file on disk reflects the data written.
65         """
66         pass
View Code

3、关闭文件

  1. 打开文件
  2. 操作文件
  3. 关闭文件 

现有文件如下 

基本操作  

1
2
3
4
5
6
7
8
= open('lyrics'#打开文件
first_line = f.readline()
print('first line:',first_line) #读一行
print('我是分隔线'.center(50,'-'))
data = f.read()# 读取剩下的所有内容,文件大时不要用
print(data) #打印文件
 
f.close() #关闭文件

打开文件的模式有:

  • r,只读模式(默认)。
  • w,只写模式。【不可读;不存在则创建;存在则删除内容;】
  • a,追加模式。【可读;   不存在则创建;存在则只追加内容;】

"+" 表示可以同时读写某个文件

  • r+,可读写文件。【可读;可写;可追加】
  • w+,写读
  • a+,同a

"U"表示在读取时,可以将 自动转换成 (与 r 或 r+ 模式同使用)

  • rU
  • r+U

"b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注)

  • rb
  • wb
  • ab

其它语法

复制代码
    def close(self): # real signature unknown; restored from __doc__
        """
        Close the file.
        
        A closed file cannot be used for further I/O operations.  close() may be
        called more than once without error.
        """
        pass

    def fileno(self, *args, **kwargs): # real signature unknown
        """ Return the underlying file descriptor (an integer). """
        pass

    def isatty(self, *args, **kwargs): # real signature unknown
        """ True if the file is connected to a TTY device. """
        pass

    def read(self, size=-1): # known case of _io.FileIO.read
        """
        注意,不一定能全读回来
        Read at most size bytes, returned as bytes.
        
        Only makes one system call, so less data may be returned than requested.
        In non-blocking mode, returns None if no data is available.
        Return an empty bytes object at EOF.
        """
        return ""

    def readable(self, *args, **kwargs): # real signature unknown
        """ True if file was opened in a read mode. """
        pass

    def readall(self, *args, **kwargs): # real signature unknown
        """
        Read all data from the file, returned as bytes.
        
        In non-blocking mode, returns as much as is immediately available,
        or None if no data is available.  Return an empty bytes object at EOF.
        """
        pass

    def readinto(self): # real signature unknown; restored from __doc__
        """ Same as RawIOBase.readinto(). """
        pass #不要用,没人知道它是干嘛用的

    def seek(self, *args, **kwargs): # real signature unknown
        """
        Move to new file position and return the file position.
        
        Argument offset is a byte count.  Optional argument whence defaults to
        SEEK_SET or 0 (offset from start of file, offset should be >= 0); other values
        are SEEK_CUR or 1 (move relative to current position, positive or negative),
        and SEEK_END or 2 (move relative to end of file, usually negative, although
        many platforms allow seeking beyond the end of a file).
        
        Note that not all file objects are seekable.
        """
        pass

    def seekable(self, *args, **kwargs): # real signature unknown
        """ True if file supports random-access. """
        pass

    def tell(self, *args, **kwargs): # real signature unknown
        """
        Current file position.
        
        Can raise OSError for non seekable files.
        """
        pass

    def truncate(self, *args, **kwargs): # real signature unknown
        """
        Truncate the file to at most size bytes and return the truncated size.
        
        Size defaults to the current file position, as returned by tell().
        The current file position is changed to the value of size.
        """
        pass

    def writable(self, *args, **kwargs): # real signature unknown
        """ True if file was opened in a write mode. """
        pass

    def write(self, *args, **kwargs): # real signature unknown
        """
        Write bytes b to file, return number written.
        
        Only makes one system call, so not all of the data may be written.
        The number of bytes actually written is returned.  In non-blocking mode,
        returns None if the write would block.
        """
        pass
复制代码

with语句

为了避免打开文件后忘记关闭,可以通过管理上下文,即:

1
2
3
with open('log','r') as f:
     
    ...

如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。

在Python 2.7 后,with又支持同时对多个文件的上下文进行管理,即:

1
2
with open('log1') as obj1, open('log2') as obj2:
    pass

 

程序练习  

程序1: 实现简单的shell sed替换功能

程序2:修改haproxy配置文件 

需求:

 需求
 原配置文件

6. 字符编码与转码

 in python2
 in python3
原文地址:https://www.cnblogs.com/francis818/p/5729818.html