2017年8月7日 星期一

[語言工具箱]Python字串、串列、字典、print、與時間格式的處理

字串處理:

2017/8/8 更新

擷取字串片段
轉載自 : http://snowdaily.pixnet.net/blog/post/81181319-python-%E6%93%B7%E5%8F%96%E5%AD%97%E4%B8%B2%E7%89%87%E6%AE%B5


abc = "This is a string"
print abc[5:]   #從第五個到最後  結果為: is a string
print abc[:5]   #從一開始到第五個  結果為: This
print abc[5:7]  #從第五個到第七個(去頭去尾) 結果為: is
此外,用法類似陣列的存取-abc被隱含轉換為字串陣列(串列)

========================================================


字串分為單引號 '  跟雙引號 " ,建議習慣用雙引號,避免特殊字元衝突!!!

"a" in AAA : 檢查a字串有沒有在AAA字串變數裡面出現,有的話回傳True.

大寫字串轉小寫:
abc = "ABCDE"
abc.lower() #字串ABCDE轉成小寫=> abcde


字串相加:
abc="123"
xyz="456"
hjk = abc[1]+xyz[1]
print(hjk) #會印出 "25" ,若要轉int可用int(hjk)

印出字串長度:
abc = "abcde
print(len(abc))   #字串長度 => 5

字串數字轉換:
int("111")  #字串111轉數字=>111
int(float("11.1")) #字串11.1轉浮點數=> 11.1 再馬上轉成 int => 11

=================================================================
串列(有順序):

在python中沒有所謂的陣列只有list(串列)與tuple
list使用方法
list=[] #宣告一個空陣列,名稱為list
串列可以塞任何東西 thread , string , int , float 甚至連serial物件都能塞,但前提是 只能塞一樣的物件在同一串列
若要像C的多維陣列使用方式來用Python串列的話
我們可以使用下列方法 :
a = ['1','2','3']
b = ['1','2','3']
c = [a,b]

若要列印a的第一個元素'1'的話,可以用print(str(c[0][0]))來顯示
就會印出'1'了

Max : max(list) #回傳串列中最大值

Min : min(list) #回傳串列中最小值

Index : list.index(i) #回傳串列中第一次索引到i值的位置

Length : len(list) #回傳串列的長度

Sum : sum(list) #加總串列

Count : list.count(value) #計算串列中出現某值的次數

Append : list.append(物件) #串列新增

Extend : list.extend(物件) #將物件附加到list 的最後,即擴增。

Insert : list.insert(addr,物件)   #example : list.insert(1,"a") 在位置1插入字串a

Remove : list.remove('a')  #移除串列list中的a值

Sort : 在List中若要排列其中的int元素的話就要使用sort功能,如下例 :
list=[1,2,4,3]

list.sort()
list => 1,2,3,4]
在這邊必須特別提到的
sorted(list)
會變成1,2,3,4
但是如果只是單純使用sorted在呼叫原本的串列
-> list
還是會變回成1,2,4,3

Pop : list.pop[i] #取出list中最後一個數值
Range
count : count 方法 可以計算某值在list出現的次數。


=================================================================
Print

在Python中,print的方式比較像JAVA而非C
然而在Python自己本身卻因為版本的分歧,連print的方式也有了差異
原因在Python在Python3的Unicode的支援度更好,所以用了跟以往Python2不一樣的方式。
例如: 時間格式的處理
1.毫秒數列印:
import datetime

print datetime.datetime.now()
處理結果 : 2016-01-08 11:42:31.804186

2.普通秒數列印:

import time
localtime = time.asctime( time.localtime(time.time()) )
print localtime
處理結果 : Fri Jan  8 09:01:11 2016
3.普通秒數列印的另一種方法
import datetime
datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
'2016-03-03 19:25:45'

或是
>>> import datetime
>>> now = datetime.datetime.now()
>>> print unicode(now.replace(microsecond=0))
2011-11-03 11:19:07

4.印一個日曆
import calendar
cal = calendar.month(2008, 1)
print cal;

處理結果 : 
January 2008
Mo Tu We Th Fr Sa Su
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31

沒有留言:

張貼留言