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


方法一:

假設有一個英文文本文件,編寫程序讀取其內容,並將其中的大寫字母變為小寫字母,小寫字母變為大寫字母。
#
先讀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)

方法二:

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='')

方法三:

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)

方法四:

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))

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM