python學習筆記一:基本資料型別
阿新 • • 發佈:2018-11-10
1、python的一切都是物件,物件是包含屬性和方法的一個整體。
2、資料型別的組成:身份 (記憶體地址,通過id方法可看它的唯一識別符號);型別(通過type方法檢視);值(資料項)
3、常用基本資料型別
- int 整型
- bool 布林
- strintg 字串
- list 列表
- tuple 元組
- dict 字典
4、資料型別的可變和不可變
- 不可變型別:int, string,tuple
- 可變型別:list,dict
5、 轉義字元
#轉義字元 print('abcd\nef')#\為轉義字元 print(r'abcd\nef')#字串前面加r表示不轉義 執行結果: abcd ef abcd\nef
6、切片
a = "abcde"
b = a[-1] #訪問最後一個元素
c = a[0:4]#訪問序列在0到4之間的元素不包括4
print(b)
print(c)
執行結果:
e
abcd
7、字串替換
a = "abcd"
print(a[0])
b = a.replace('d','def')
print(b)
print(a.find('d'))#字串查詢
執行結果:
a
abcdef
3
8、字串拼接
#【1】直接相加 a = 'my name is xiaobin' b = 'tong' c = a + b print(c) 執行結果: my name is xiaobintong #【2】佔位符 print('my name is %s xiaobin' % 'tong')#%s為字串佔位符,%d為數字佔位符 print('my name is %s xiaobin,i\'m %s years old' % ('tong',24)) print('my name is {1}, i\'m {0} years old'.format('24','tongxiaobin'))#用format方法 執行結果: my name is tong xiaobin my name is tong xiaobin,i'm 24 years old my name is tongxiaobin, i'm 24 years old #【3】join a = '123' b = '456' c = '789' d = ''.join([a,b,c]) e = ';'.join([a,b,c]) print(d) print(e) 執行結果: 123456789 123;456;789
9、檔案操作:‘r’-read; 'w'-write;‘a’-append(在最後新增)
#寫操作 d = open('1.txt','w') d.write('hello world\nmy name is tongxiaobin') d.close() #讀操作 e = open('1.txt','r') print(e.readline())#按行讀取 print(e.readline()) 執行結果: hello world my name is tongxiaobin #末尾新增操作 a = open('1.txt','a') a.write('\ncome from anhui') a.close() 開啟檔案結果為: hello world my name is tongxiaobinfdsd come from anhui
10、linecache模組
import linecache
linecache.getline('1.txt',2)
執行結果:
'my name is tongxiaobin\n'
linecache.getlines('1.txt')
執行結果:
['hello world\n', 'my name is tongxiaobin\n', 'come from anhui\n']