一、内容

Python基础第五天

 

 

 

 

练习1

题目:写函数,用户传入修改的文件名,与要修改的内容,执行函数,完成批量修改操作

图示:

Python基础第五天

 代码:

import os
def revise(f,r,x):
    with open(f,'r',encoding='utf-8') as read_f,\
        open('.li.swp','w',encoding='utf-8') as write_f:
        for line in read_f:
            if r in line:
                line = line.replace(r,x)
            write_f.write(line)
    os.remove(f)
    os.rename('.li.swp',f)
revise('a.txt','knight','dark')

输出结果:

 a.txt原文件内容:

 Python基础第五天

运行该程序后,a.txt文件的内容:

Python基础第五天

 

 

 

练习2

题目:写函数,计算传入字符串中【数字】、【字母】、【空格】 以及 【其他】的个数

图示:

Python基础第五天

代码:

user_input = input('Please enter:')
def count(w):
    a = 0
    b = 0
    c = 0
    d = 0
    for i in w:
        if i.isdigit():
            a += 1
        elif i.isalpha():
            b += 1
        elif i.isspace():
            c += 1
        else:
            d += 1
    print('The number entered is %s,\nThe letter entered is %s,\nThe number of spaces entered is %s\nOther input is %s'%(a,b,c,d))
count(user_input)

输出结果:

例:

Python基础第五天

 

 

练习3

题目:写函数,判断用户传入的对象(字符串、列表、元组)长度是否大于5。

图示:

Python基础第五天

代码:

def func_len(w):
    if isinstance(w,str) or isinstance(w,tuple) or isinstance(w,list):
    # isinstance是Python中的一个内建函数。是用来判断一个对象的变量类型。
        if len(w)>5:
            print('length>5')
        else:
            print('length<5')
    else:
        print('not str,not list,not tuple.')
func_len('knight')
func_len([1,2,3,4,5,6,7])
func_len((1,2,3))

# 当用户输入的不是字符串、元组、列表时
func_len({'a':1,'b':2})

输出结果:

length>5
length>5
length<5
not str,not list,not tuple.
View Code

相关文章:

  • 2021-11-04
  • 2021-10-16
  • 2021-06-09
  • 2021-11-11
  • 2021-12-15
  • 2021-10-27
  • 2021-07-29
  • 2021-11-07
猜你喜欢
  • 2021-11-22
  • 2021-06-23
  • 2021-07-06
  • 2021-06-07
  • 2021-11-30
  • 2021-12-06
  • 2021-12-16
相关资源
相似解决方案