python基础学习之文件操作&函数

1、文件处理相关

1、编码问题

①python2与python3中的默认编码:

py2默认使用ASCII码,py3默认使用utf-8

②为什么会出现中文乱码,中文乱码的情况有哪些?

#sys.stdout.encoding,默认就是locale的编码,print会用sys.stdout.encoding去encode()成字节流,交给terminal显示。所以,locale需要与terminal一致,才能正确print打印出中文

下面还是直接给大家介绍下可以正确打印出中文的方式咯:

终端为utf-8,locale为zh_CN.GBK

终端为utf-8,locale为zh_CN.UTF-8

终端为GBK,locale为zh_CN.GBK

终端为GBK,locale为zh_CN.UTF-8

2、如何进行编码转换

字符串在python内部中是采用unicode的编码方式,所以其他语言先decode转换成unicode编码,再encode转换成utf-8编码。

3、#-*-coding:utf-8-*-的作用

起到编码声明的作用

4、解释py2 bytes vs py3 bytes的区别

python2将strings处理为原生的bytes类型,而不是unicode(python2 str == bytes)

python3所有的string均是unicode类型(python3需要通过unicode)

string -> encode -> bytes

bytes -> decode -> string

5、文件处理

①r和rb的区别:r是读模式,而rb是二进制读模式,即数据读到的内容直接是二进制bytes模式

②解释open中以下三个参数的作用:

open(f_name,'r',encoding='utf-8'):f_name是文件名,r是模式,encoding是编码方式

2、函数基础

1、写函数,计算传入参数的和。(动态传参)

def func_sum(x,y):

  return x+y             或 lambda x,y:x+y

2、写函数,用户传入修改的文件名,与要修改的内容,执行函数,完成整个文件的批量修改操作

#修改列表中字符串(首字母大写)

def file_daxie(file):

  a = []

  for i in file:

  b = i.capitalize()

  a.append(b)

print(a)
View Code

3、写函数,检查用户传入的对象(字符串、列表、元组)的每一个元素是否有空内容

def file_k(file):
    n = 0
    for i in file:
        if i == ' ':
            n += 1
    print('有%s个空'%n)
View Code

4、写函数,检查传入字典的每一个value的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。

dic = {'k1':'v1v1','k2':[11,22,33,44]}
def func(i):
    for k,v in i.items():
        if len(v) > 2:
            dic[k] = v[ :2]
        else:
                continue
    return i

print(func(dic))
View Code

5、解释闭包的概念

闭包(closure)是函数式编程的重要的语法结构。函数式编程是一种编程范式(注:面向过程编程和面向对象编程也是编程范式)

闭包是一种组织代码的结构,它同样能提高代码的可重复使用性。

3、函数进阶

1、写函数,返回一个扑克牌列表,里面有52项,每一项是一个元组

例如:[(‘红心’,2),(‘草花’,2),……(‘黑桃’,‘A’)]

def cards():
    num = []
    for i in range(2, 11):
        num.append(i)
    num.extend(['J', 'Q', 'K', 'A'])
    type = ['红心', '草花', '方块', '黑桃']
    result = []
    for i in num:
        for j in type:
            result.append((j,i))
    return result
print(cards())
View Code

2、写函数,传入n个数,返回字典{‘max’:最大值,‘min’:最小值}

例如:min_max(2,5,7,8,4)

返回:{‘max’:8,‘min’:2}

def max_min(*args):
    the_max = args[0]
    the_min = args[0]
    for i in args:
        if i > the_max:
            the_max = i
        else:
            the_min = i
    return {'max': the_max, 'min': the_min}
res = max_min(2, 4, 6, 48, -16, 486)
print(res)
View Code

猜你喜欢

转载自www.cnblogs.com/ding-jing/p/8823517.html