輸入和輸出
編程有時(shí)候需要和用戶交互奏路,比如讓用戶輸入內(nèi)容然后打印結(jié)果給他爱榕,我們可以用input()函數(shù)和print函數(shù)。
輸出的話花履,我們可以用str類中的很多方法芽世,比如用rjust方法獲得一個(gè)正符合特殊長(zhǎng)度的字符串。更多的細(xì)節(jié)可以看help(str)诡壁。
Input from user (用戶輸入)
我們讓用戶輸入一個(gè)文本济瓢,然后判斷是否是回文(正反讀都一樣,如madam妹卿,radar)
def reverse(text):
return text[::-1]
def is_palindrome(text):
return text==reverse(text)
something=input("Please enter text:")
if is_palindrome(something):
print("It's palindrome!")
else:
print("It's not palindrome.")
這樣當(dāng)用戶輸入一個(gè)回文時(shí)打印It's palindrome!旺矾,否則打印It's not palindrome.
File(文件)
我們可以在文件類中通過讀、寫等相應(yīng)方法去打開一個(gè)文件去讀取或?qū)懭肱μ詈笠?em>close方法關(guān)閉宠漩。
poem='''\
Programming is fun
When the works is done
if you wanna make your work also fun
use Python!
'''
#open fow 'w'riting
f=open('peom.txt','w')
#write text to file
f.write(poem)
#close the file
f.close()
#if no mode is spesfied,'r'ead mode is assumed by default
f=open('peom.txt')
while True:
line=f.readline()
#Zero lingth indicates EOF(End Of File)
if len(line)==0:
break
print(line,end='')
#close the file
f.close()
Output:
Programming is fun
When the works is done
if you wanna make your work also fun
use Python!
文件打開的默認(rèn)參數(shù)是‘r’(讀),另外還有‘w’(寫)和‘a(chǎn)’(添加)懊直,同時(shí)分文本形式(‘t’)和字節(jié)形式(‘b’)
Pickle(腌)
Python提供了Pickle的標(biāo)準(zhǔn)模塊扒吁,可以用來(lái)將任意的Python對(duì)象放入一個(gè)文件中,需要時(shí)再取出室囊,這叫持久的儲(chǔ)存對(duì)象雕崩。
import pickle
# The name of the file where we will store the object
shoplistfile = 'shoplist.data'
# The list of things to buy
shoplist = ['apple', 'mango', 'carrot']
# Write to the file
f = open(shoplistfile, 'wb')
# Dump the object to a file
pickle.dump(shoplist, f)
f.close()
# Destroy the shoplist variable
del shoplist
# Read back from the storage
f = open(shoplistfile, 'rb')
# Load the object from the file
storedlist = pickle.load(f)
print(storedlist)
Output:
['apple', 'mango', 'carrot']
在文件里儲(chǔ)存一個(gè)對(duì)象,首先以寫融撞、二進(jìn)制模式打開一個(gè)file 對(duì)象盼铁,然后調(diào)
用pickle 模塊的dump 函數(shù),這個(gè)過程稱為pickling 尝偎。
接下來(lái)饶火,我們用pickle 模塊的返回對(duì)象的load 函數(shù)重新取回對(duì)象鹏控。這個(gè)過程稱之
為unpickling 。
Unicode
不過英文或者非英文肤寝,我們都可以用Unicode來(lái)表述出來(lái)当辐。Python3里面已經(jīng)默認(rèn)存儲(chǔ)字符串變量在Unicode,但Python2涉及到非英文的鲤看,要在前面加‘u’來(lái)提示使用Unicode缘揪。
當(dāng)數(shù)據(jù)發(fā)送到因特網(wǎng)時(shí),我們需要用二進(jìn)制义桂,這樣計(jì)算機(jī)才容易懂找筝。我們稱轉(zhuǎn)換Unicode碼到二進(jìn)制為encoding(編碼),一個(gè)比較流行的編碼是UTF-8慷吊。我們可以用一個(gè)簡(jiǎn)單的關(guān)鍵字語(yǔ)法來(lái)讀寫我們的open函數(shù)袖裕。
# encoding=utf-8
import io
f = io.open("abc.txt", "wt", encoding="utf-8")
f.write(u"Imagine non-English language here")
f.close()
text = io.open("abc.txt", encoding="utf-8").read()
print(text)
下一步要接觸“exceptions”了,這幾章的內(nèi)容是是而非罢浇,感覺掌握了陆赋,又沒有非常熟練,工作忙又沉不下心來(lái)嚷闭。