[Python] Python 學習記錄

來源:互聯網
上載者:User

標籤:否則   字串   html   and   自動連接   3.0   span   href   字元   

1.概論

弱類型 一個變數能被賦值時能與原類型不同 

x = 1

x = "1"  #不加分號,給x賦值為int後再次賦值為string是可行的

 

與或非 and or not

 

/  #除法的結果是浮點數, 9 / 3 = 3.0

// #結果是整數 10 // 3 = 3

 

空值為None(相當於null)

內建類型  Numbers(整數和浮點數), Strings,Lists

 

print(‘‘) 

print("%%") #%  字串列印單引號和雙引號皆可

print(r‘C:\Users\local‘)  #C:\User\local raw 表示不轉義 相當於C#中@

字串跨多行

print(‘‘‘ 內容

內容‘‘‘) 

‘‘‘內容‘‘‘

 

2.字串

字元編碼

ASCII 使用一個位元組 包含127個編碼 (大小寫英文、數字、特殊符號)

Unicode 使用兩個位元組表示一個字元 (偏僻的使用4個位元組)

Utf-8(8-bit Unicode Transformation Format) 針對Unicode的可變長編碼

屬於ASCII的字元用一個位元組,漢字使用兩個位元組編碼 完全相容ASCII

電腦記憶體中統一使用Unicode編碼,需要儲存或傳輸時轉換為Utf-8編碼

 

ord() #取字元的整數表示

chr() #把編碼轉換為字元

print(‘\u4e2d\u6587‘) #中文 

 

x = b‘ABC‘ #x為bytes 一個字元佔用一個位元組

x = ‘ABC‘  #x為str

 

字串編碼(bytes str互轉)

str->bytes ‘STR‘.encode(‘ascii‘)  # utf-8

bytes->str b‘STR‘.decode(‘ascii‘)

 

字串格式化

‘%d,%f,%s,%x‘ % (2333,3.14,‘Python str‘,0x23)

‘%2d-%02d‘ %(3,1)   #3-01

‘%.2f‘ % 3.1415  #3.14

 

字串可以用 + 串連

用 * 用來重複字串 3 * ‘a‘ #aaa

print(‘a‘ ‘b‘)   #ab 這樣a和b會自動連接起來,少寫個 + 

word = ‘Python‘ 

print(word[0])  #p

print(word[-1])   #n 倒數第一個

word[0:2]   #Py

word[2:5]   #tho

word[:2]     #Py

word[4:]     #on

word[-2:]    #word[-2] + word[-1] on

字串有不可變性 word[0] = ‘A‘ 會報錯

 

 

3.list 

x = [1, 2, 3, 4]

和字串一樣index用起來比較方便

x[0] #1

x[1:2] #[2, 3]

x[-2:] #[3, 4]

y = [4, 5, 6, 7]

x + y  #[1, 2, 3, 4, 5, 6, 7]   集合的並操作

 

tuple 

與list類型,但其中的元素不可變

 

4.分區

有點Matlab的感覺

L = [1,2,3]

L[0:2]  L[0] L[1]

L[1:]  #L[1] 到最後一個元素 或者寫成L[1:-1]

L[-1] 最後一個元素

L[:10:2] #前10個數,每兩個取一個 [0,2,4,6,8]

 

5.map() & reduce()

map(func, [1,2,3])

將[1,2,3]中每個元素作為參數執行一次func

 

reduce(func, [1,2,3])

func(func(1,2),3)

 

練習解答

輸入:[‘adam‘, ‘LISA‘, ‘barT‘],輸出:[‘Adam‘, ‘Lisa‘, ‘Bart‘]

 def normalize(name):     first = name[0].upper()     for i in name[1:]:             first = first + i.lower()     return firstL1 = [‘adam‘, ‘LISA‘, ‘barT‘]L2 = list(map(normalize, L1))print(L2)

 

 

 

6. filter()

filter(func,[1,2,3,4])

和map類似,以每個元素為參數調用func,返回為ture的保留,否則丟棄

 

sorted([2,3,4,5,6,7],key = comparer, reverse = false)

傳一個比較方法即可快速實現排序

 

參考連結

字串和編碼-廖雪峰的官方網站

https://docs.python.org/3/tutorial/introduction.html

[Python] Python 學習記錄

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.