1. 命名規(guī)則
- 變量名有大小寫字母、數(shù)字瞻坝、下劃線組成杏瞻,首字母不可為數(shù)字和下劃線所刀;
- 區(qū)分大小寫捞挥;
- 變量名不能為Python保留字。
2. 邏輯型
定義:False
True
運算符:&
|
not
3. 數(shù)值型
運算符:+
-
*
/
# 取整 //
7 // 4
--> 1
# 取余 %
7 % 4
--> 3
# 乘方 **
2 ** 3
--> 8
# 注意浮點數(shù)計算
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. 字符型
定義: ''
'' ''
# 反斜杠(\)表示轉(zhuǎn)義字符
print('hello,\n how are you?')
--> hello,
--> how are you?
# 不想讓反斜杠轉(zhuǎn)義,可在字符串前面加 r 讹俊,表示原始字符
print(r'hello,\n how are you?)
--> hello,\n how are you?
# 反斜杠還可以作為續(xù)行符,表示下一行是上一行延續(xù)
# 還可以使用 """ ...""" 或者 '''...'''跨多行
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
# 檢測開頭和結(jié)尾
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
# 查找字符串吕晌,區(qū)分大小寫
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"