在寫python指令碼時,通常會遇到一些函式,下面對這些的函式用法做乙個總結:
1、strip()函式
作用:移除字串頭尾指定的字元(預設為空格或換行符)或字串行。
案例:
2、split()函式#案例
a=' asdjfadf ' #建立物件
a.strip()
out[75]: 'asdjfadf'
#刪除開頭和結尾還有字元a
a.strip('a')
out[89]: 'sdjfadf'
作用:通過指定分隔符對字串進行切片,如果引數 num 有指定值,則僅分隔 num 個子字串
案例:
3、replace()函式#語法:str.split(str="", num=string.count(str))
a='12;15;24;56;56'
a.split('\;')
out[78]: ['12;15;24;56;56']
例2:str = "line1-abcdef \nline2-abc \nline4-abcd"
print str.split( )
['line1-abcdef', 'line2-abc', 'line4-abcd']
print str.split(' ', 1 )
['line1-abcdef', '\nline2-abc \nline4-abcd']
#注:str -- 分隔符,預設為所有的空字元,包括空格、換行(\n)、製表符(\t)等。
num -- 分割次數
作用:把字串中的 old(舊字串) 替換成 new(新字串),如果指定第三個引數max,則替換不超過 max 次。
4、json模組#語法:
str.replace(old, new[, max])
old -- 將被替換的子字串。
new -- 新字串,用於替換old子字串。
max -- 可選字串, 替換不超過 max 次
返回乙個新字串
a='asdjfadf'
a.replace('df','fff')
out[99]: 'asdjfafff'
a='25;52;65;23;55;66'
a.replace(';',',')
out[100]: '25,52,65,23,55,66'
#list和replace,split結合使用
a='25;52;65;23;55;66'
b=list(a.replace(';',',').split(','))
bout[118]: ['25', '52', '65', '23', '55', '66']
json模組主要包含兩個函式:dumps和loads
描述如下:
json.dumps :將 python 物件編碼成 json 字串
python 原始型別向 json 型別的轉化對照表:import json
#建立資料集
data=
json = json.dumps(data) #將data轉化為json型別
json
out[122]: ''
#使用引數讓 json 資料格式化輸出:
print json.dumps(,sort_keys=true,indent=4,separators=(',',':'))
python
json
dict
object
list, tuple
array
str, unicode
string
int, long, float
number
true
true
false
false
none
null
json.loads:將已編碼的 json 字串解碼為 python 物件
json 型別轉換到 python 的型別對照表:import json
#建立python json物件
jsondata = '';
text = json.loads(jsondata)
text
out[132]:
json
python
object
dict
array
list
string
unicode
number (int)
int, long
number (real)
float
true
true
false
false
null
none
5、callable
用法:callable(object),返回乙個布林值(true/false)。
作用:該方法用來檢測物件是否可被呼叫,可被呼叫指的是物件能否使用()括號的方法呼叫。
6、set()
用法:set(object)
作用:函式建立乙個無序不重複元素集,可進行邏輯關係判斷,刪除重複資料,還可以計算交集、差集、並集等。
7、xrange()a=set('goodman')
b=set('runningman')
aout[2]:
bout[3]:
#求並集
a|bout[4]:
#求交集
out[5]:
#求差集
out[6]:
用法:xrange(stop)/xrange(start,stop[,step])
作用:和range完全相同,所不同的是生成的不是乙個陣列,而是乙個生成器。
引數說明:start:計數從start開始。預設是從0開始,xrange(5)等價於xrange(0,5)
stop:計算到stop結束,但不包括暫時stop
step:步長,預設為1,xrange(0,5)等價於xrange(0,5,1)
先寫那麼多,以後會慢慢增加~
Python中部分知識總結
input輸出的為字串,運用強制轉換,轉換為你所需要的型別 python中 兩個數相除,得到的是完全計算後的結果,例10 8 1.25 而 表示兩個數相除,結果中的小數部分直接被捨去,例10 8 1,3.0 2 1.0 表示冪運算子,例3 2 9 冪運算子比其左側的一元操作符優先順序高,比其右側的一...
Keras中部分函式的使用總結
1 keras中concatenate和add層的不同 在網路結構的設計上,經常說densenet和inception中更多採用的是concatenate操作,而resnet更多採用的add操作,那麼這兩個操作有什麼異同呢?concatenate操作是網路結構設計中很重要的一種操作,經常用於將特徵聯...
MySQL中部分時間函式的使用
mysql中,一周預設是從週日到周一的,這和國外的習慣一樣,而中國是周一到週日算一周。所以在統計諸如 本週的資料 時,就需要特殊注意。看到很多網上的文章,在處理這個點上寫很多 其實mysql提供的week和yearweek函式中已經考慮到了這一點。week函式介紹 通常,一年的正常年份為365天,閏...