python.png
Python數據類型
1. 命名規則
- 變量名有大小寫字母、數字、下劃線組成,首字母不可為數字和下劃線;
- 區分大小寫;
- 變量名不能為Python保留字。
2. 邏輯型
定義:False
True
運算符:&
|
not
3. 數值型
運算符:+
-
*
/
# 取整 //
7 // 4
--> 1
# 取余 %
7 % 4
--> 3
# 乘方 **
2 ** 3
--> 8
# 注意浮點數計算
a = 2.1;
b = 4.2;
a + b
--> 6.300000001
(a + b) == 6.3
--> False
# WHY?
a = 2.3;
b = 4.2;
(a + b) == 6.5
--> True
4. 字符型
定義: ''
'' ''
# 反斜杠(\)表示轉義字符
print('hello,\n how are you?')
--> hello,
--> how are you?
# 不想讓反斜杠轉義,可在字符串前面加 r ,表示原始字符
print(r'hello,\n how are you?)
--> hello,\n how are you?
# 反斜杠還可以作為續行符,表示下一行是上一行延續
# 還可以使用 """ ...""" 或者 '''...'''跨多行
s = '''
abcd
efg
'''
print(s)
--> abcd
--> efg
# 字符串之間可以使用 '+' 或者 '*'
print('abc' + 'def', 'my' * 3)
--> abcdef mymymy
# Python 索引方式兩種:
# 1.從左到右,索引從0開始;
# 2.從右到左,索引從-1開始;
# 沒有單獨的字符,一個字符就是長度為1的字符串
Word = 'Python'
print(Word[0],Word[-1])
--> P n
s = 'a'
len('s')
--> 1
# 對字符串切片,獲取一段子串
# 用冒號分開兩個索引,形式為 變量[頭下標:尾下標]
# 截取范圍前閉后開,且兩個索引都可以省略
Str = 'iLovePython'
Str[0:2]
--> 'iL'
Str[3:]
--> 'vePython'
Str[:5]
--> 'iLove'
Str[:]
--> 'iLovePython'
Str[-1:]
--> 'n'
Str[-5:-1]
--> 'ytho'
# Python字符串不可改變
Str[0] = 'a'
--> TypeError: 'str' object does not support item assignment
# 檢測開頭和結尾
url = 'http://www.python.org'
url.startswith('http:') # starts 有 s
--> True
url.endswith('.com') # endswith 有 s
--> False
choices = ('http:','https')
url.startswith(choices)
--> True
choices = ['http:','https']
url.startswith(choices)
--> False
# 查找字符串,區分大小寫
Str = 'Python'
Str.find('y')
--> 1
Str.find('Y')
--> -1
# 忽略大小寫的查找
import re
Str = 'Python,YELL'
re.findall('y', Str, flags = re.IGNORECASE)
--> ['y', 'Y']
# 查找與替換
text = 'hello, how, what, why'
text.replace('hello', 'hi')
--> 'hi, how, what, why'
text
--> 'hello, how, what, why'
text = text.replace('hello', 'hi')
text
--> 'hi, how, what, why'
# 忽略大小寫的替換
import re
text = 'UPPER PYTHON, lower python, Mixed Python'
re.sub('python','java',text,flags = re.IGNORECASE)
--> 'UPPER java, lower java, Mixed java'
# 合并拼接字符串
parts = ['yo','what\'s','up']
' ' .join(parts)
--> "yo what's up"
',' .join(parts)
--> "yo,what's,up"