天天看點

python 邏輯運算符 資料類型_Python運算符和資料類型

a = 10

a = -10

a = 080

int(3.5) 傳回的結果是3

2、布爾類型(bool)

布爾型就兩種值,一種True一種False

B =True

b = False

3、浮點型(float)

a = 0.0a = 10.20

a = -21.9

a = -20

round(float,ndigits)

Float代表數字,ndgits代表的是精度,大規則是四舍五入。

例子:

round(9.615,2) 傳回9.62

4、字元串

a = 'abcde'len(a) 5有5個字元

a + 'f' 'abcdef'a * 10重複10次

'abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde'

字元串常用的方法:

find 查找字元串下标

strip 字元串過濾空格(最前面和最後面的空格)

replace(old,new) 替換字元串内容,老的替換成新的

find(sub) 字元串中查找sub字元串的内容,如果找到,傳回sub字元串的下标

format 字元串格式化

startswith(str) 以字元串str開頭的

endswith(str) 以字元串str結尾的

[:] 分片,前開後閉,提取從開頭到結尾的整個字元串

a = " hello world "

print(a.find("e")) # 傳回2

print(a.find("w")) # 傳回7

print(a.strip()) # hello world

print(a.replace("w","a")) # 傳回hello aorld

name = "yang jian"

age = 18

print("my name is {0},age is {1}".format(name,age))

a = "abcde"

a[1:3] 'bc' 從第二個開始取,到第四個,但是不包括第四個。

a[::1] 'abcde' 取完a後跳一步,然後取b後跳一步.....

a[::2] 'ace' 取完a後跳2步,取c,取完c後跳2步,取e

a[-4:-2] 'bc'

a[-2:-4:-1] 'dc' 從右到左

5、清單

清單的資料項可以是多鐘類型。

l = ['a','b','c','1','2','3']

清單常用方法:

append() 在清單末尾增加一個元素,沒有傳回值

pop() 末尾删除一個元素,傳回删除的元素

index() l.index("a")傳回元素a的下标

insert() l.insert(3,"ling") 在指定的位置插入元素

remove(value) l.remove("b") 删除一個指定值得元素

reverse() l.reverse() 反序 無傳回值

sort(self,cmp=None,key=None,reverse=False) l.sort() 排序

>>> list3 = ['a',1,(1,),['hello','python']]

>>>list3

['a', 1, (1,), ['hello', 'python']]

>>> list3[0] = 'b'改變元素

>>>list3

['b', 1, (1,), ['hello', 'python']]

清單也可以相加、相乘

list1 +list2

list1 * 2list1.append('b')

del list3[-1] 删除清單中的元素

dellist3 删除清單

list1.remove(1)

list1.insert(index,value) 在index之前插入

>>> list1 = [1,2,3,1]

>>>list1

[1, 2, 3, 1]

>>> list1.remove(1) 如果有重複的話,會删除清單裡面第一次出現的元素

>>>list1

[2, 3, 1]

2 inlist1

list1.insert(1,list4) 在索引1之前插入一個空的清單,但是list4得在插入之前先定義,那麼要在空的清單裡插入元素,怎麼辦呢?

list1.insert(1,list4)

>>>list1

[2, [], 3, 1]

>>> list1[1].append('a')

>>>list1

[2, ['a'], 3, 1]

>>>list1

[1, 2, 3, ['a']]

>>> range(5)

[0, 1, 2, 3, 4]

>>> list1.extend(range(5)) 疊代

>>>list1

[1, 2, 3, ['a'], 0, 1, 2, 3, 4]

>>> list1.extend('abcde') 把'abcde'拆分開的,裡面也可以放元組,用括号括起來的。list1.extend(('t1','t2'))

>>>list1

[1, 2, 3, ['a'], 0, 1, 2, 3, 4, 'a', 'b', 'c', 'd', 'e']

6、元組

元組是序列的一種,值是不可變的。

>>> t = ('a',1,(1,)) 這裡加逗号是因為,隻有一個元素的話,類型會是該元素的類型,隻有加逗号才會是tuple類型。元組裡面可以混合放多種類型的元素。

>>>t

('a', 1, (1,))

>>> t1 = (1)

>>>type(t1)

隻有一個元素,沒有加逗号,類型為int。

>>> t1 = (1,)

>>>type(t1)

隻有一個元素,加了逗号,類型為tuple。

>>> t = (a,'b','c')

>>>t

('abcde', 'b', 'c')

>>> first,second,third =t

>>>first

'abcde'

>>>second

'b'

>>>third

'c'

>>> t = ('a','c','f')

>>> t.index('a')

>>> t.index('c')

1

>>> help(t.index) 使用幫助