假設有一個英文文本文件,編寫程序讀取其內容,並將其中的大寫字母變爲小寫字母,小寫字母變爲大寫字母。

方法一:spa

假設有一個英文文本文件,編寫程序讀取其內容,並將其中的大寫字母變爲小寫字母,小寫字母變爲大寫字母。
#
先讀r,後改,最後寫入w f=open('demo.txt','r') s=f.readlines() f.close() r=[i.swapcase() for i in s] #大小寫轉換 f=open('demo1.txt','w+') f.writelines(r) f.seek(0) ss=f.read() f.close() print('轉換結果爲:',ss)

方法二:code

ls="Just five months on and Ryan Reynolds is back in Beijing. "
print('原始文件爲:',ls) print('轉換結果爲:',end='') for i in fn: if ord(i)>=65 and ord(i)<=90 : print(i.lower(),end='') elif ord(i)>=97 and ord(i)<=122: print(i.upper(),end='') else: print(i,end='')

方法三:blog

ls="Just five months on and Ryan Reynolds is back in Beijing. "
print('原始文件爲:',ls) print('轉換結果爲:',end='') res=''
for i in ls: if i.islower(): res+=i.upper() elif i.isupper(): res+=i.lower() else: res+=i print(res)

方法四:it

def uptolow(filepath): res='' with open(filepath,'r') as f: ss=f.readlines() for s in ss: for i in s: if i.islower(): res+=i.upper() elif i.isupper(): res+=i.lower() else: res+=i return res if __name__ =="__main__": filepath='demo.txt'
    print(uptolow(filepath))
相關文章
相關標籤/搜索