標籤:邏輯運算子 布爾 浮點 join for 保留 append code 沒有
Python的邏輯運算子
數字運算子: + -
/ %
關係運算子:a==b, a>b, a<b, a!=b
賦值運算子:a=b(把b的值賦給a), +=, a+=b, -=, =, /=
邏輯運算子: and, or, not, (if a==b and a!=10:)
1、 整型 int
a=10print(a)
2、 布爾值bool分為兩種,一種是 True,一種是 False
>=1 True<=0 False
3、 float 浮點值
a=3.141592653m = round(a,2) # 保留兩位小數print(m)
round(float,ndigits)
float代表數字,ndigits代表精度
大的規則是四捨五入
4、字串 str ‘abc‘ "abc" ‘‘‘abc‘‘‘
string = ‘abcadefgahiagh‘print(string)
5、find 尋找字串,如果找到就返回字串開始的下標,如果沒有找到則返回-1
print(string[0]) # 列印下標為0的值print(string[3]) # 列印下標為3的值print(string[:]) # 列印所有值result = string.find(‘def‘)print(result)# 3 返回下標3
6、 replace 替換
print(string.replace("a","AAA"))
7、split 分隔字元
# join(可迭代對象) 一般為list字串newlist = string.strip().split("a")print(newlist)print(" ### ".strip().join(newlist))
8、 strip() 去除字串前後的Null 字元
string.strip()print("My string is : %s" % string)print("My string is : {0}".format(string)) # 推薦使用,效率最高print("hello" + "world")
9、列表是有一系列特定順序排列的元素組成的,
可以把字串、數字、字典等任何對象加入到列表中,
其中的元素之間沒有任何關係,列表也是內建下標的,預設從0開始
l = [1,2,3.1415926,‘a‘,‘b‘,‘c‘,True,{"name":"zyy"}]print(l)# [1, 2, 3.1415926, ‘a‘, ‘b‘, ‘c‘, True, {‘name‘: ‘zyy‘}]
10、字典有哪些常用方法呢
l.append("hello")print(l)# [1, 2, 3.1415926, ‘a‘, ‘b‘, ‘c‘, True, {‘name‘: ‘zyy‘}, ‘hello‘]
11、 pop 刪除元素 ,預設刪除最後一個元素
l.pop()print(l)# [1, 2, 3.1415926, ‘a‘, ‘b‘, ‘c‘, True, {‘name‘: ‘zyy‘}]l.pop(2) # 刪除下標為2的元素print(l)# [1, 2, ‘a‘, ‘b‘, ‘c‘, True, {‘name‘: ‘zyy‘}]
12、remove 刪除元素,直接刪除元素,remove(value)
# index(value) 尋找元素對應的下標print(l.index("a"))# 2m = [1,34,234,54,543,5,533,4,5432]print(m)# [1, 34, 234, 54, 543, 5, 533, 4, 5432]m.sort() #print(m)# [1, 4, 5, 34, 54, 234, 533, 543, 5432]m.reverse()print(m)# [5432, 543, 533, 234, 54, 34, 5, 4, 1]
13、 insert 插入新的元素 insert(index, value)
m.insert(3,"hello")print(m)
Python資料類型