python学习之第二天

本节内容

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

1. 列表、元组操作

列表是我们最以后最常用的数据类型之一,通过列表可以对数据实现最方便的存储、修改等操作

定义列表


1

names = [‘Alex‘,"Tenglan",‘Eric‘]

通过下标访问列表中的元素,下标从0开始计数


1

2

3

4

5

6

7

8

>>> names[0]

‘Alex‘

>>> names[2]

‘Eric‘

>>> names[-1]

‘Eric‘

>>> names[-2#还可以倒着取

‘Tenglan‘

切片:取多个元素  

 

追加

 

插入

 

修改

 

删除

 

扩展

 

拷贝

 

copy真的这么简单么?那我还讲个屁。。。

统计

 

排序&翻转

 

获取下标

 

元组

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

语法


1

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

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

程序练习

请闭眼写出以下程序。

程序:购物车程序

需求:

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

2. 字符串操作    

 一些蛋疼的语法

3. 字典操作

字典一种key - value 的数据类型,使用就像我们上学用的字典,通过笔划、字母来查对应页的详细内容。

语法:

info = {
    ‘stu1101‘: "TengLan Wu",
    ‘stu1102‘: "LongZe Luola",
    ‘stu1103‘: "XiaoZe Maliya",
}

字典的特性:

  • dict是无序的
  • key必须是唯一的,so 天生去重

增加

 

修改

 

删除

 

查找

 

多级字典嵌套及操作

 

其它姿势

 

循环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.集合操作

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

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

常用操作

 

5. 文件操作

对文件操作流程

  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 \n \r\n自动转换成 \n (与 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. 字符编码与转码

详细文章:

http://www.cnblogs.com/luotianshuai/articles/5735051.html

http://www.diveintopython3.net/strings.html

需知:

1.在python2默认编码是ASCII, python3里默认是utf-8

2.unicode 分为 utf-32(占4个字节),utf-16(占两个字节),utf-8(占1-4个字节), so utf-8就是unicode

3.在py3中encode,在转码的同时还会把string 变成bytes类型,decode在解码的同时还会把bytes变回string

 in python2

 in python3

7.  内置函数

分类: Python自动化开发之路

时间: 2024-08-28 12:46:31

python学习之第二天的相关文章

python学习的第二天

今天是学习的第二天,贾队长今天主要学习了python的数据类型和变量.不同的数据,需要定义不同的数据类型.在Python中,能够直接处理(难道还有间接处理或者别的什么处理?需要去更多了解这一点)的数据类型有以下几种:1.整数.2.浮点数(也就是小数,但为什么要这样叫?).3.字符串,就是用‘’或者“”包含的任意文本.还有很多的转义字符\(转义字符很多还需要大量的学习了解)4.布尔值,一个布尔值只有True和false两种值.在python中,可以直接用True和False,但是要注意大小写.还可

菜鸟Python学习笔记第二天:关于Python黑客。

2016年1月5日 星期四 天气:还好 一直不知道自己为什么要去学Python,其实Python能做到的Java都可以做到,Python有的有点Java也有,而且Java还是必修课,可是就是不愿意去学Java,后来看到了<Linux黑客的python编程之道>然后发现了一些自己感兴趣的事,每个IT男都有一个黑客梦,我也不例外,所以继续开始Python写习. 因为要准备高数考试,所有以很多东西不能去仔细学习. 就深深的记住了几句话: 第一句:调试器就是黑客的眼睛.刚开始不懂什么是调试器:但是从眼

Python学习笔记第二十六周(Django补充)

一.基于jQuery的ajax实现(最底层方法:$.jax()) $.ajax( url: type:''POST" ) $.get(url,[data],[callback],[type])  #callback是发送成功后就执行的函数,type是告诉服务器需要什么数据,type:text|html|json|script $.post(url,[data],[callback],[type]) 例子: $.get('/jquery_get/',{name:'gavin'}) //name关键

Python学习【第二篇】Python入门

Python安装 windows: 1.下载安装包 https://www.python.org/downloads/ 2.安装 默认安装路径:C:\python27 3.配置环境变量 [右键计算机]-->[属性]-->[高级系统设置]-->[高级]-->[环境变量]-->[在第二个内容框中找到 变量名为Path 的一行,双击] --> [Python安装目录追加到变值值中,用 : 分割] 如:原来的值;C:\python27,前面有分号 linux: 自带python

Python学习系列-----第二章 操作符与表达式

2.1 数学运算和赋值的简便方法 例如: 2.2 优先级 在python中运算符有优先级之分,高优先级的运算符先执行,低优先级的运算符后执行.下面是运算符优先级:(同一行的运算符具有相同的优先级) 2.3 改变优先级 可以用' () '来改变优先级,先执行括号里的表达式. 2.4 结合顺序 计算机在执行的时候,是有顺序的,运算符结合顺序通常是从左到右,例如:2+3+5,也有运算符的结合顺序是从右到左的,例如:a=3; 2.5 表达式 不要在意中文释义,下面就是一个表达式.例如:a=a+b;

python 学习 之 第二章(条件、循环和其他语句)

1.    简单的条件执行语句( if ) num = int( input("enter a number\n") ) if num == 0: print("num = 0\n") else: print("num != 0\n") 稍微复杂一点的执行语句: num = int( input("enter a number\n") ) if num == 0: print("num = 0\n") el

Python学习(第二章)

一. 变量 1. type(变量名)  可以查看该变量的类型 2. 关于字符串的两个运算符 + 与 * ,分别执行 拼接 和 重复 操作 3. 格式化输出 %s 字符串 %d 整型 (%06d 保留六位前面补0) %f 浮点数 (%.2f 保留小数点后2位) %% 百分号% name = '小明' print('我的名字叫%s,请多多关照!'%name) student_no = 100 print('我的学号是%06d'%student_no) price = 8.5 weight = 7.5

Python学习,第二课 - 字符编码

关于字符编码 python解释器在加载 .py 文件中的代码时,会对内容进行编码(默认ascill) ASCII(American Standard Code for Information Interchange,美国标准信息交换代码)是基于拉丁字母的一套电脑编码系统,主要用于显示现代英语和其他西欧语言,其最多只能用 8 位来表示(一个字节),即:2**8 = 256-1,所以,ASCII码最多只能表示 255 个符号. 关于中文 为了处理汉字,程序员设计了用于简体中文的GB2312和用于繁体

Python学习笔记第二十四五周(Django补充)

目录: 内容: 1.render_to_reponse() 不同于render,render_to_response()不用包含request,直接写template中文件 2.locals() 如果views文件中的函数里变量过多的话,可以在render或render_to_response()里面直接增加render(request,'index.html',locals())这样在前端界面渲染的时候可以直接写变量名