a = ‘20’ 字串的結構
print(type(a)) type檢視資料型別
b=int(a) int 為整形
print(b) 輸出轉換之後的型別
print(type(b)) 檢視改變之後的型別
s = ‘hello’
對字串的每個元素進行編號: 下標從0開始,每個下標都是整數
通過下標來取出字串中的元素
print(s[4])
s = “hello python,hello world”
s.replace(",", " “) 將,替換為空格,此時s本身沒有改變
s = s.replace(”,", " ") 通過重新賦值,s本身改變
s = “hello python, hello world”
c = s.split()
print©
print(type©)
用一對[]包括的資料,稱為列表(list)
列表中存放的資料型別都可以
l = [12, 34]
ll = [‘12’, 23, 45.6]
l = [12,‘20’,1.2]
for i in l:
print(i,type(i))
l = []
l.extend(‘hello’)
print(l)
l = []
l.append([1,2,3])
l.extend([1,2,3,4])
print(l)
l = [1, 2, 3, 4, 5, 6]
l[1] = 7
print(l)
l[1] = ‘ofehso’
print(l)
l = [1, 2, 3.15, ‘hso’, False]
1 <class ‘int’>
3.15 <class ‘float’>
hso <class ‘str’>
False <class ‘bool’>
for c in l:
print(c,type©)
l.pop()
print(l)
del l
l[1] = 2.15
a = l.count(‘hso’)
print(a)
list=[12, [34, [‘13’, 43, 67], 78]]
list[0] = 12.5
print(list)
l = [1,2,3,1.5]
l.sort(reverse=True)
print(l)
a = (1,2,3)
print(a)
元組不能增、刪、改其中的資料,但是可以直接刪除整個元組
del a
a = {“name”:“海航是”, “age”:21, “gender”:“男”}
字典的資料結構
{鍵:值}, 兩者合稱為鍵值對,多個鍵值對之間","隔開
d = {“a”:1}
print(a)
print(a[“name”])
print(a[“age”])
print(a[“gender”])
a[“name”] = 10 修改
print(a)
a[“gender”] = ‘女’ 修改
print(a)
a[‘price’] = 21002 修改
print(a)
a = {“name”:“海航是”, “age”:21, “gender”:“男”}
del a[“age”]
print(a)
del a
a = {}
name = input(‘輸入名:’)
a[“name”] = name
a [“age”] = int(input(‘年齡:’))
a [“address”] =input(‘住址:’)
a [“heigth”] = int(input(“身高(cm):”))
a [‘weighi’] = float(input(“輸入體重(kg)”))
print(a)
遍歷字串
s = “hello world”
for i in s:
print(i)
遍歷列表
l = [1, 2, 3, 4]
for i in l:
print(i)
遍歷元組
a = (1, 2, 3, 4, 5)
for i in a:
print(i)
遍歷字典
ddd = {“a”: 1, “b”: 2, “c”: 3, “d”: 4}
for i in ddd:
print(i)
for i in ddd.keys():
print(i)
for i in ddd.values():
print(i)
for i in ddd.items():
print(i)
s = {1, 2, 3}
s2 = set()
l = []
d = {}
a = ()
集合特性
元素唯一
元素無序
集合方法
新增
add:新增一個元素
update:將每個元素依次新增
remove:按元素的值刪除,不存在,報錯
discard:按元素的值刪除, 不存在,不報錯
pop: 隨機刪除
s = set()
s.add(“人生苦點,我用python”)
s.update(‘hello python’)
print(s)
s = {‘e’, ‘h’, ‘helo’, ‘l’, ‘o’}
s.discard(‘z’)
print(s)
s.remove(‘z’)
print(s)