二、python 數值型別(字串切片)和資料型別(元組)
阿新 • • 發佈:2018-12-26
linux下 可以安裝python工具;yum install -y ipython
ipython支援 命令補全
數值型別
數值型別分為整形 ,長整形,浮點型,複數行
整形:平常使用的整數
長整型:很大的整數。 type 為 long
浮點:帶小數點的數字
想要3/2 得到精確數字,將其中一個數字變成浮點行即可
當行數比較多的時候可以使用三引號註釋
使用換行符
>>> a="hello \n word"
>>> a
'hello \n word'
>>> print a
hello
word
用索引在字串中取值,(序列的切片)
>>> a="abcdef" >>> a[0] 'a' >>> a[5] 'f' >>> a[-1] 'f' >>> a[0:2] # 取多個字串時多算後一個座標,因為並不會包含改座標下的字元 'ab' >>> >>> a[::1] 'abcdef' >>> a[::2] #2個::後面代表步數, 寫1代表走一步取數,選2代表走2步取數 'ace' >>> >>> a[:] # : 前面不寫代表預設從0開始,後面不寫代表到-1 結束 'abcdef' >>> a[-5:-3] #也可以反過來取數 'bc' >>> a[-3:-5:-1] #其中 -1代表反向(從左到右取值),預設是從右到左 'dc'
python資料型別-元組
字串的一些基本操作
>>> a="abcde" >>> len(a) # 長度為5 5 >>> a 'abcde' >>> a+"f" # +代表拼接字串 'abcdef' >>> a 'abcde' >>> a*3 # * 代表將a列印3次 'abcdeabcdeabcde' >>> "#"*19 '###################' >>> "a" in a # in代表是否包含,a包含了‘a’ 所以為ture True >>> "f" in a #a中不包含f,所以為false False >>> "f" not in a True >>> max(a) # a中最大值數值為e 'e' >>> min(a) # a中最小數值為a 'a' >>> cmp(a,'abcde') #將a 與其他字串進行對比,一樣為0,比其大為正數,反之為負數 0 >>> cmp(a,'abcdef') -1 >>> cmp(a+'f','abcdef') 0 >>> cmp(a+'g','abcdef') 1 >>>
元組
元組是不可變的一組字串
>>> c=(1,) #元組 要 括號加逗號才能表示
>>> type(c)
<type 'tuple'>
>>>
>>> d=(1,a,(2,))
>>> d
(1, 'abcde', (2,))
>>> type(d)
<type 'tuple'>
<type 'tuple'>
>>> d[0]
1
>>> d[1]
'abcde'
>>>
元組也可以索引,切片
元組取值:
>>>
>>> d
(1, 'abcde', (2,))
>>> a,b,c=d #用變數來標識 元組d裡面的字串
>>> a
1
>>> b
'abcde'
>>> c
(2,)
>>>
# 這個count是計數的意思,那麼t.count應該是統計value在t中出現的次數。
我這邊做了個實驗:
>>> t
('a', 'b', 'a', 'b')
>>> t.count('b')
2
>>> t1
('a', 'b', 'a', 'b', 'a', 'b', 'a', 'b')
>>> t1.count('a')
4