標籤:python
一、Python數字類型
1、數字類型有整數型,浮點型以及一些較為少見的類型,數字類型支援數學運算
加減乘除取餘In [1]: 23 + 45Out[1]: 68In [2]: 1.7 + 2Out[2]: 3.7In [3]: 2 * 10Out[3]: 20In [4]: 10 / 2Out[4]: 5In [5]: 23 - 45Out[5]: -22In [6]: 100 & 7Out[6]: 4
2、python的數學模組math
In [7]: import mathmath的屬性及方法In [8]: math.math.acos math.cos math.factorial math.ldexp math.sinmath.acosh math.cosh math.floor math.lgamma math.sinhmath.asin math.degrees math.fmod math.log math.sqrtmath.asinh math.e math.frexp math.log10 math.tanmath.atan math.erf math.fsum math.log1p math.tanhmath.atan2 math.erfc math.gamma math.modf math.truncmath.atanh math.exp math.hypot math.pi math.ceil math.expm1 math.isinf math.pow math.copysign math.fabs math.isnan math.radians 常用函數階乘:In [13]: math.factorial(54)Out[13]: 230843697339241380472092742683027581083278564571807941132288000000000000L開平方In [14]: math.sqrt(54)Out[14]: 7.3484692283495345常量piIn [15]: math.piOut[15]: 3.141592653589793
3、隨機數模組random
In [16]: import random1.產生隨機數In [17]: random.random()Out[17]: 0.101435172235644362.給定隨機數產生範圍In [18]: random.uniform(2,3)Out[18]: 2.8343477251262748In [19]: random.uniform(100,3)Out[19]: 84.883344129396963.給定範圍產生隨機整數In [20]: random.randint(3,4)Out[20]: 34.隨機播放器In [23]: random.choice([1,‘a‘,3.4])Out[23]: 1In [24]: random.choice([1,‘a‘,3.4])Out[24]: 3.4In [25]: random.choice([1,‘a‘,3.4])Out[25]: ‘a‘5.隨機重新排序,原地修改In [26]: a = [1,2,3,4,5]In [27]: random.shuffle(a)In [28]: aOut[28]: [3, 1, 5, 2, 4]6.隨機切片,不影響原有序列In [34]: random.sample(a,2)Out[34]: [1, 2]In [35]: aOut[35]: [1, 2, 3, 4, 5]
二、Python字串
字串是單個字元的字串的序列,是不可變的
1、字串序列操作
1.定義字串In [36]: a = ‘apache‘2.字串索引(左起從0開始,右起從-1開始)In [37]: a[0]Out[37]: ‘a‘In [38]: a[1]Out[38]: ‘p‘In [39]: a[-1]Out[39]: ‘e‘3.字串切片In [40]: a[1:3]Out[40]: ‘pa‘In [41]: a[2:]Out[41]: ‘ache‘In [42]: a[:2]Out[42]: ‘ap‘In [43]: a[:-1]Out[43]: ‘apach‘In [44]: a[-3:-1]Out[44]: ‘ch‘4.字串複製In [45]: b = a[:]In [46]: bOut[46]: ‘apache‘5.字串的不可變性In [47]: a + ‘ web server‘Out[47]: ‘apache web server‘In [48]: aOut[48]: ‘apache‘In [49]: a * 3Out[49]: ‘apacheapacheapache‘In [50]: aOut[50]: ‘apache‘
2、字串方法
常用的字串方法如下1.統計字串中字元出現的次數In [54]: a.count(‘a‘)Out[54]: 2In [55]: a.count(‘p‘)Out[55]: 12.尋找字元位於字串中的位移量In [57]: a.find(‘a‘)Out[57]: 0In [58]: a.find(‘p‘)Out[58]: 13.字元替換,不修改中繼資料In [59]: a.replace(‘a‘,‘b‘)Out[59]: ‘bpbche‘In [60]: aOut[60]: ‘apache‘4.大寫轉換In [61]: a.upper()Out[61]: ‘APACHE‘5.測試字串In [62]: a.isalpha()Out[62]: True6.字串拆分In [63]: b = "11:22:33:44"In [64]: b.split(‘:‘)Out[64]: [‘11‘, ‘22‘, ‘33‘, ‘44‘]7.去字串尾部空格In [68]: c = ‘apache\n‘In [69]: c = c.rstrip()In [70]: cOut[70]: ‘apache‘8.python3.0新特性:替代In [71]: ‘{0},2,{1},4‘.format(‘1‘,‘3‘)Out[71]: ‘1,2,3,4‘
本文出自 “linux啟航” 部落格,請務必保留此出處http://jiayimeng.blog.51cto.com/10604001/1896157
Python 學習日記第一篇