练习题学习

晨练练习题:
1 写一个函数,实现遍历一个数字和字母参杂的字符串,如果碰到字母则替换成*,最后隔开的数字作为整体计算求和。
如”ab34aa243dd78eww89”,则替换成
的结果为:”342437889”,求和结果为:”7915**17”

def func(s):
result=""
num=0
for i in s:
if i.isalpha():
if num!=0:
result+=str(num)
num=0
result+="*"
else:
num+=int(i)
if num!=0:
result+=str(num)
return result

print(func(“ab34aa243dd78eww89”))

执行结果:
7915*17

第二种:

encoding = UTF-8

import re
s= “ab34aa243dd78eww89”
result =""

s=re.sub(r"[a-z]","",s)
arr1=re.split("\
+",s) #[’’, ‘34’, ‘243’, ‘78’, ‘89’]
for i in range(len(arr1)):
count=0
if arr1[i].isdigit():
for j in arr1[i]:
count+=int(j)
if count!=0:
arr1[i] = str(count)

arr2=re.split("\d+",s)#[’’, '’, ‘’, '*’, ‘’]

for i in range(len(arr1)):
result+=arr1[i]+arr2[i]

print(result)

第三种:
def get_data(data):
result=""
for i in data:
if i.isalpha():
result+="*"
else:
result+=i
return result

def get_sum(num):
result=""
temp=num.split("")
for i in temp:
sum1=0
if len(i)==0:
result+="
"
elif len(i)==1:
result+=i
else:
for j in i:
sum1+=int(j)
result+=str(sum1)
return result

if name==“main”:
data1=“ab34aa243dd78eww89”
result1=get_data(data1)
print(get_sum(result1))

2 一个字符串i am learning,请依照如下规则转换为数字
abcd–5, efgh–10, ijkl–15, mnop–20, qrst–25, uvwx–30 yz–35
转换正确结果为:15 520 151052520152010

dict1={‘a’:5,‘b’:5,‘c’:5,‘d’:5,‘e’:10,‘f’:10,‘g’:10,‘h’:10,‘i’:15,‘j’:15,‘k’:15,‘l’:15,‘m’:20,‘n’:20,‘o’:20,‘p’:20,‘q’:25,‘r’:25,‘s’:25,‘t’:25,‘u’:30,‘v’:30,‘w’:30,‘x’:30,‘y’:35,‘z’:35}
s=“i am learning”
result=""
for i in s:
if i.isalpha():
result+=str(dict1[i])
else:
result+=i

print(result)

执行结果:
15 520 151052520152010

第二种:
def get_num(num):
b=""
for i in num.lower():
if i.isspace():
b+=i
else:
value=(ord(i)-97)//4
b+=str(value*5+5)
return b

a=“i am learning”
print(get_num(a))

执行结果:
15 520 151052520152010

第三种:
rule=“abcd–5,efgh–10,ijkl–15,mnop–20,qrst–25,uvwx–30,yz–35”
rule=rule.split(",")
s=“i am learning”
result=""
for i in s:
for r in rule:
if i in r:
part=r.split("–")[-1]
result +=part
break
else:
result+=i

print (result)

执行结果:
15 520 151052520152010

3 从控制台输入一串字母,判断是否是连续相同字母,是则输出True,否则输出False。

s=input(“请输入一串字母:”)
flag=True
for i in range(len(s)-1):
if ord(s[i])+1!=ord(s[i+1]):
flag=False
break

print(flag)

执行结果:
请输入一串字母:abcdefg
True

请输入一串字母:3566l
False

请输入一串字母:abcdfh
False

s=input(“请输入一串字母:”)
flag=True
for i in range(len(s)-1):
if ord(s[i])!=ord(s[i+1]):
flag=False
break

print(flag)

执行结果:
请输入一串字母:aaaaa
True

请输入一串字母:aaaaab
False

第二种:
def judge_str():
s=input(“请输入一串字符串”)

if s[0]*len(s)==s and ((s[0]>='a' and s[0]<='z') or (s[0]>='A' and s[0]<='Z')):
    return True
else:
    return False

print (judge_str())

第三种:
def get_result(data):
for i in range(len(data)-1):
if data[i].isalpha():
if data[i]!=data[i+1]:
return False
else:
print(“请输入字母!”)
return False
return True

if name==“main”:
for i in range(3):
data1=input(“请输入一串字母:”)
print(get_result(data1))

文件:

import os
os.linesep
‘\r\n’

fp = open(“e:\a.txt”,“w”)
fp.write(“a\r\nb\rc\nd”)
8

fp.close()
fp = open(“e:\a.txt”,“r”) #默认会将\r转换为\n
fp.read()
‘a\n\nb\nc\nd’

fp.seek(0,0)回到文件最开始的位置

fp=open(“c:\code\test1.txt”,“w+”,encoding=“utf-8”)
fp.read()
‘’

fp.write(“aaaabbb”)
7

fp.read()
‘’

fp.seek(0,0)
0

fp.read()
‘aaaabbb’

fp.write(“njkjkkkk”)
8

fp.read()
‘’

fp.seek(0,0)
0

fp.read()
‘aaaabbbnjkjkkkk’

fp=open(“c:\code\test1.txt”,“r+”,encoding=“utf-8”)
fp.read()
‘aaaabbbnjkjkkkk’

fp.tell()
15

fp.read()
‘’

fp.write(“cccc”)
4

fp.read()
‘’

fp.seek(0,0)
0

fp.read()
‘aaaabbbnjkjkkkkcccc’

fp.seek(0,0)
0

fp.write(“zzz”)
3

fp.seek(0,0)
0

fp.read()
‘zzzabbbnjkjkkkkcccc’

fp=open(“c:\code\test1.txt”,“a+”,encoding=“utf-8”)
fp.tell()
19

fp.read()
‘’

fp.write(“yan”)
3

fp.seek(0,0)
0

fp.read()
‘zzzabbbnjkjkkkkccccyan’

fp.seek(0,0)
0

fp.write(“jin”)
3

fp.seek(0,0)
0

fp.read()
‘zzzabbbnjkjkkkkccccyanjin’

readline()比readlines()更省内存
fp=open(“c:\code\test1.txt”,“r+”,encoding=“utf-8”)
while 1:
content=fp.readline()
print(content,end="")
if content=="":
break

执行结果:
zzz
abb
bnjk
jkkkk
cccc
yan
jin

fp=open(“c:\code\test1.txt”,“r+”,encoding=“utf-8”)
fp.seek(0,0)
print(len(fp.readlines())) #可以用来统计行数
fp.close()

执行结果:
7

with open(“c:\code\test1.txt”,“r+”,encoding=“utf-8”) as f:
print(type(f))
for line in f:
print(line,end="")

执行结果:
<class ‘_io.TextIOWrapper’> #迭代器
zzz
abb
bnjk
jkkkk
cccc
yan
jin

with:上下文管理,使用with后,先进入__enter__进行初始化工作并返回一个值,在运行结束后,在__exit__中进行自动清理的工作,并退出。
class Sample:
def enter(self):
print(“In enter()”)
return “Foo”

def __exit__(self, type, value, trace):
    print("In __exit__()")

def get_sample():
return Sample()

with get_sample() as sample:
print(“sample:”, sample)

执行结果:
In enter()
sample: Foo
In exit()

file.closed 返回true如果文件已被关闭,否则返回false。
file.mode 返回被打开文件的访问模式。
file.name 返回文件的名称。

fp=open(“c:\code\test1.txt”,“r+”)
fp.read(1) #每次读指定的固定长度,直到文件结束
‘z’

fp.read(5)
‘zz\nab’

fp.read(5)
‘b\nbnj’

fp.read(5)
‘k\njkk’

fp.read(5)
‘kk\ncc’

fp.read(5)
‘cc\nya’

fp.read(5)
‘n\njin’

fp.read(5)
‘’

fp.read(5)
‘’

fp.seek(0,0)
0

fp.readline(3) #跟read()固定读取有点不一样,一行最后一次读不够指定固定长时不会读下一行的内容
‘zzz’

fp.readline(3)
‘\n’

fp.readline(3)
‘abb’

fp.readline(4)
‘\n’

file.readlines([sizeint])
读取所有行并返回列表,若给定sizeint>0,返回总和大约为sizeint字节的行, 实际读取值可能比 sizeint 较大, 因为需要填充缓冲区。

j=0
for i in range(26,0,-1):
print(i)
tmp=chr(i+71+j)+str(i)
j+=2
with open(“c:\code\test2.txt”,“a+”,encoding=“utf-8”) as f:
f.write(tmp+’\n’)

执行结果:
test2.txt文件
a26
b25
c24
d23
e22
f21
g20
h19
i18
j17
k16
l15
m14
n13
o12
p11
q10
r9
s8
t7
u6
v5
w4
x3
y2
z1

with open(“c:\code\test3.txt”, ‘w’) as fp:
for i in range(26):
fp.write(chr(ord(“a”) + i) + str(26 - i) + “\n”)

with open(“c:\code\test3.txt”, ‘r’) as fp:
print(fp.read())

执行结果:
a26
b25
c24
d23
e22
f21
g20
h19
i18
j17
k16
l15
m14
n13
o12
p11
q10
r9
s8
t7
u6
v5
w4
x3
y2
z1

fp.flush()强制将缓冲区中的内容写入硬盘

fp = open(“c:\code\test3.txt”,“w+”)
fp.read()
‘1234b’

fp.seek(4,0)
4

fp.write(“a”)
1

fp.seek(0,0)
0

fp.read()
‘1234a’

fp.write(“axxx\nbxxxx\n”)
11

fp.tell()
18

fp.seek(0,0)

在文件中加入一行内容
with open(“c:\code\test3.txt”, ‘r+’) as fp:
data=fp.readlines()
data.insert(1,“12333\n”)
fp.seek(0,0)
fp.writelines(data)
fp.seek(0, 0)
print(fp.read())

执行结果:
aaa
12333
dgjgkkgkkg
dgjgkkgkkgfff
fff

吴老师代码:
fp = open(“e:\a.txt”,“r+”)
content=fp.readlines()
content.insert(1,“gloryroad\n”)
fp.seek(0,0)
fp.writelines(content)
fp.close()

读文件的第二行的数据
with open(“c:\code\test3.txt”, ‘r+’) as fp:
print(fp.readlines()[1]) #可以通过后面的索引坐标来指定读取某一行

count=0
for line in fp:
… count+=1
… if count ==2: #也可以通过这种遍历来指定读取某一行
… print(line)

b’gloryroad\r\n’

fp= open(“c:\code\test4.txt”,‘rb+’)
fp.read()
b’123\r\n456\r\nabcdfdfd\r\nabcdfdfd\r\n’

fp.seek(5,1)
35

fp.read()
b’’

fp.read(-10,1)
Traceback (most recent call last):
File “”, line 1, in
TypeError: read() takes at most 1 argument (2 given)

fp.seek(-10,1)
25

fp.read()
b’dfd\r\n’

fp.seek(5,1) #参数二为1时,是相对于当前位置向前或向后移动游标
35

fp.seek(0,0)
0

fp.seek(5,1)
5

fp.read()
b’456\r\nabcdfdfd\r\nabcdfdfd\r\n’

fp.seek(0,0)
0

fp.seek(5,2) #参数二为2时,是相对于最后的位置向前或向后移动游标
35

fp.read()
b’’

fp.seek(-5,2)
25

fp.read()
b’dfd\r\n’

fp.truncate():把文件裁成规定的大小(单位为字节),默认的是裁到当前文件操作标记的位置。如果size比文件的大小还要大,依据系统的不同可能是不改变文件,也可能是用0把文件补到相应的大小,也可能是以一些随机的内容加上去

fp=open(“c:\code\test5.txt”,“r+”)
lines= fp.readlines()
fp.seek(0,0)
for line in lines:
if line.strip():
fp.write(line)

fp.close()

fp=open(“c:\code\test5.txt”,“r+”)
lines= fp.readlines()
fp.seek(0,0)
for line in lines:
if not line.strip()=="":
fp.write(line)

fp.close()

exec(“a=1”)
a
1

exec(“a=2*2”)
a
4

eval(“2*3”)
6

序列化:把东西存文件里
反序列化:把东西从文件中取出来

-- coding: utf-8 --

import pickle as p
shoplistfile = ‘c:\code\shoplist.data’

the name of the file where we will store the object

shoplist = [‘apple’, ‘mango’, ‘carrot’]

Write to the file

f = open(shoplistfile, ‘wb’)
p.dump(shoplist, f) # dump the object to a file
f.close()
del shoplist # remove the shoplist

Read back from the storage

f = open(shoplistfile,‘rb’)
storedlist = p.load(f)
print (‘从文件读取的列表对象:’,storedlist)

执行结果:
从文件读取的列表对象: [‘apple’, ‘mango’, ‘carrot’]

先进先出

import pickle as p
shoplistfile = ‘c:\code\shoplist.data’

the name of the file where we will store the object

shoplist = [‘apple’, ‘mango’, ‘carrot’]
animallist=[‘hippo’,‘rabbit’]

Write to the file

f = open(shoplistfile, ‘wb’)
p.dump(shoplist, f) # dump the object to a file
p.dump(animallist,f)
f.close()
del shoplist # remove the shoplist
del animallist

Read back from the storage

f = open(shoplistfile,‘rb’)
storedlist = p.load(f)
animallist= p.load(f)
print (storedlist)
print (animallist)

执行结果:
[‘apple’, ‘mango’, ‘carrot’] #先进先出
[‘hippo’, ‘rabbit’]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值