## python 基礎 :數值,鏈表,字串

很多網站上都有python教程,不一而足,本篇教程會結合我在實際開發程序中遇到的問題,總結出很多有意思的小tricks,我會把你當做python小白來看待,所以不要心急和擔心,一步步的討教一下python的招式,
### 數值
python是一門動態語言,它可以在運行時宣告和使用變數,同時它也是一種強型別的語言,這一點有別于PHP,python會提供強制型別轉換的方法,與java類似,但是PHP的話編譯器會自動識別你所運用的變數到底是哪種型別,
**注意**:‘123’可以通過int()來轉化成123,但是別的非數字字串就不可
```
更準確來說,它也滿足遇強則強的型別強制轉換規則,最明顯的就是在兩個數相除的時候,
```
同時python也是支持復數運算的一門語言,虛部由一個后綴"j"或者"J"來表示,帶有非零實部的復數記為"real+imagj",或者通過`complex(real, img)`函式創建,記得以前c++中最經典的一些題目就是多載+運算子,使其可以支持復數運算,來看幾個例子:
```
>>> 1j * 1J
(-1+0j)
>>> 1j * complex(0,1)
(-1+0j)
>>> 3+1j*3
(3+3j)
>>> (3+1j)*3
(9+3j)
>>> (1+2j)/(1+1j)
(1.5+0.5j)
```
假設復數為z,那么它的實部就為z.real 虛部就為z.imag
```
>>> a=1.5+0.5j
>>> a.real
1.5
>>> a.imag
0.5
```
**注意**
不能將復數轉化成常用的變數型別,你可以用abs函式取模,
##### trick:
`在shell互動模式下,最近一次的計算結果保存在變數_(下劃線)中,這樣就可以很方便的進行運算操作,`
### 字串
python里面有一個string的module,我們先從最基本的開始講起,
想必你對轉義字符并不陌生,在python中也保留了這一轉義傳統,加入你在字符后面打上\,說明接下來的字串是\之前的邏輯后綴:
```
>>>hello = "This is a rather long string containing\n \several lines of text just as you would do in C.\n\
Note that whitespace at the beginning of the line is
\significant."
print hello
```
將得到
```
This is a rather long string containing
several lines of text just as you would do in C.
Note that whitespace at the beginning of the line is significant.
```
那么很明顯,‘\n’就是我們熟悉的換行,\是邏輯繼續符號,具體的輸出格式你需要根據自己的shell跑跑看,
##### trick:
`如果我們創建一個“行”("raw")字串,\ n序列就不會轉為換行,原始碼中的反斜杠和換行符n都會做為字串中的資料處理`
```
hello = r"This is a rather long string containing\n\
several lines of text much as you would do in C."
print hello
```
你將得到:
```
This is a rather long string containing\n\
several lines of text much as you would do in C.
```
但是:
```
r allow \t to be interpreted as the two characters \ and t
也就是說:r‘\t’得到的是\\t
```
`如果你還是嫌太麻煩,那么就用三引號(""")來包裹字串,這樣的話兩個三引號之間不需要進行行尾換行處理,`
`同時,就像你想的那樣,字串可以相加可以乘以一個數字進行成倍的復制,更令人吃驚的時兩個字串的值可以自動的粘黏在一起:`
```
>>>'str''ing'
>>>'string'
```
`但是這個功能僅僅針對字串常量,`
接下來要講到的一個字串的功能跟python中的陣列有莫大的關聯,其實這句話是廢話,一般而言字串也不過就是一個儲存在記憶體中的字符陣列,但是我這句話的本意是想表達,python的陣列,更嚴格來講是list,有一個很強大的功能,那就是`切片`,
初學者可能還無法領會切片使用的奧義,那么我們來舉幾個例子你就能體會為什么這個功能是很多人選擇python的理由,
```
+---+---+---+---+---+
| H | e | l | p | A |
+---+---+---+---+---+
0 1 2 3 4 5
-5 -4 -3 -2 -1
上圖展示了python串列下標的情況,python的list可以進行負索引操作:
>>> word[-1] # The last character
'A'
>>> word[-2] # The last-but-one character
'p'
>>> word[-2:] # The last two characters
'pA'
>>> word[:-2] # Everything except the last two
'Hel'
切片操作有一個很有用的不變性:
>>> word[:2] + word[2:]
'HelpA'
>>> word[:3] + word[3:]
'HelpA'
```
所以現在你回頭看看你以前熟悉的那些硬語言,沒有哪一種是可以像這樣操作陣列或者串列的,這樣就給資料結構和演算法提供的莫大的方便,鏈表的操作跟上述的操作道理是一樣的,這里不贅述了,
###### 下面我們來看看string module
在介紹python中的核心概念module之前,相比你們都嘗試過import這個功能,沒錯,python的強大之處就在于它的第三方包,這些包在python簡潔的基礎之上又進行了整理,使得語法更加的簡單明了,更加地人性化,這里我們以string這個module為例子,介紹一下有關module的使用,希望大家可以舉一反三,
無論對于哪一種語言來講,字串的操作是重中之重,為此大部分語言都將其作為一個單獨的類或者包列出來,提供對字串操作的方法,python也不例外,
首先打開你的終端(linux用戶,windows就cmd吧),分別輸入以下命令:
1 python
2 import stirng
3 dir(string)
會出現以下一大坨:
```
['Formatter', 'Template', '_TemplateMetaclass', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_float', '_idmap', '_idmapL', '_int', '_long', '_multimap', '_re', 'ascii_letters', 'ascii_lowercase', 'ascii_uppercase', 'atof', 'atof_error', 'atoi', 'atoi_error', 'atol', 'atol_error', 'capitalize', 'capwords', 'center', 'count', 'digits', 'expandtabs', 'find', 'hexdigits', 'index', 'index_error', 'join', 'joinfields', 'letters', 'ljust', 'lower', 'lowercase', 'lstrip', 'maketrans', 'octdigits', 'printable', 'punctuation', 'replace', 'rfind', 'rindex', 'rjust', 'rsplit', 'rstrip', 'split', 'splitfields', 'strip', 'swapcase', 'translate', 'upper', 'uppercase', 'whitespace', 'zfill']
```
這些就是string這個module里面所包含的默認屬性以及方法(屬于類以級別,可按照java中的類方法理解),那些奇奇怪怪的下劃線看不懂不要緊,下一篇文章我會解釋,如果想知道其中某個函式比如find的用法,請在終端這么做:`help(string.find)`,那么就會出現:
```
Help on function find in module string:
find(s, *args)
find(s, sub [,start [,end]]) -> in
Return the lowest index in s where substring sub is found,
such that sub is contained within s[start,end]. Optional
arguments start and end are interpreted as in slice notation.
Return -1 on failure.
(END)
```
它會給你一個抽象方法和一個具體方法,如上,星號看不懂也沒有關系,下章會講,僅僅先當做引數,
```
注意:
在終端中,(END)是高亮的,你閱讀完了以后,直接按'q',就會回傳到>>>提示符,可以繼續操作,不然這個既不想vim也不像emacs的東西會搞得你頭大,
```
那么string中常見的幾個函式用法給大家列一下,具體情況具體help
```
string.atof(s)# Convert to float
string.atoi(s)# Convert to integer
string.atol(s)# Convert to long
string.count(s,pattern)# Count occurrences of pattern in s
string.find(s,pattern)# Find pattern in s
string.split(s, sep)# String a string
string.join(strlist, sep) # Join a list of string
string.replace(s,old,new) # Replace occurrences of old with new
```
`高度預警:`
函式'atoi'可以把string型別變數轉化為int型別變數,但是僅限于轉數字字串型別
```
s='string'
s=string.atoi(s)#錯誤
s = '123'
s=string.atoi(s)#正確
```
推薦一下我建的python學習交流扣扣qun:850973621,群里有免費的視頻教程,開發工具、
電子書籍、專案原始碼分享,一起交流學習,一起進步!



作者:牧師Harray
鏈接:https://www.jianshu.com/p/34b111bf27ce
來源:簡書
著作權歸作者所有,商業轉載請聯系作者獲得授權,非商業轉載請注明出處,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/232886.html
標籤:Python
上一篇:花兩萬學的python,總結了一點初學者的小技巧,免費送給大家
下一篇:威聯通(NAS)搭建個人音樂中心
