close

(1) 儲存檔案

with open("Output.txt","w")as text_file:

text_file.write("Purchase Amount: {0}".format(TotalAmount)) 

或 > = python2.7 可以使用 {} 代替 {0} 

with open("Output.txt","w")as text_file:

print("Purchase Amount: {}".format(TotalAmount))

(2) 字串的運算: 字串資料也支援下列幾種運算方式
(2.1)  字串相加 : 兩個字串資料作相加(+)的運算

x = 'Hello, '
y = 'World'
print x+y

這段程式碼會印出 Hello, World

(2.2)產生重複字串

字串資料可以與整數進行 * 的運算,這表示要將字串重複幾次:

x = 'Cat'
print x * 3

這樣螢幕會輸出 CatCatCat

(2.3)取出字串部份內容

想要取出字串部份的內容,不管是單一字元,或是一段範圍的字串,可以使用 [] 運算子來操作:

x = 'Hello, World.'
print x[7]
print hello[0:6]

 這段程式碼會分別在螢幕上印出 "W" 及 "Hello,"

(2.4)計算字串長度

如果要計算字串的長度,直接使用 len() 函式就可以了。

+

 

x = 'Hello, World.'
print len(x)

就會在螢幕上印出 13

 

 

(3)使用 List 資料

 

List 資料型態可以用來表示或處理排列在一起的資料,在 Python 裡是使用中括號( [ 及 ] )包起來表示,而 List 裡的資料可以是任何資料型態:記住,List 資料的索引是*從0開始**

 

a = [1, 3, 'abc', 7, "xyz"]
print a[3]

 

 

螢幕上印出: 7 

(3.1)選取某個元素

單一索引值取出 List 資料中的某一份資料

(3.2)選取一段範圍

除了使用單一索引值取得 List 中單一元素,也可以設定範圍取出一段部份資料,如:

print a[1:3]

螢幕上印出: [3, 'abc']

(4)Dictionary

建立一個 Dictionary 物件

d = {'python': 'Large constricting snakes.', 'ruby': 'A precious stone that is a red corundum.'}

 使用 [] 這個運算子的時候,我們就可以拿到它的 Value 了 

 

print d['python']

 

則會印出

 

Large constricting snakes.

 

(4.1)取得 Dictionary 物件中 Key 的個數

 

print len(d)

 

則會印出:2

(4.2)新增或修改一筆資料

 

d['game'] = 'Activity engaged in for diversion or amusement.'
print d

 

(4.3)刪除一筆資料

del d['game']
print d

 

 

 

arrow
arrow
    全站熱搜

    stanley 發表在 痞客邦 留言(0) 人氣()