文章目錄
- 編寫簡單的程序
- 一、標識符 (Identifiers)及關鍵字
- 命名規則:
- 命名慣例:
- 關鍵字
- 二、變量與賦值 (Variables & Assignment)
- 變量定義:
- 多重賦值:
- 變量交換:(很方便喲)
- 三、輸入與輸出 (Input & Output)
- 輸入:
- 輸出:
- 四、數值 (Numbers)
- 數值類型:
- 數值運算:
- 五、字符串 (Strings)
- 字符串定義:
- 字符串操作:
- 字符串格式化:
- 常用字符串函數
- 1. 基本操作函數
- 2. 判斷類函數
- 3. 分割和連接
- 4. 格式化函數
- 字符串應用實例
- 1. 數據清洗
- 2. 密碼強度檢查
- 3. 文本分析
- 4. 字符串加密
- 5. URL處理
- 高級字符串操作
- 1. 正則表達式 (re模塊)
- 2. 字符串模板 (string.Template)
- 3. 字符串對齊
- 類型轉換
- 資源庫
編寫簡單的程序
一、標識符 (Identifiers)及關鍵字
標識符是用于標識變量、函數、類、模塊等對象的名字。
命名規則:
- 由字母、數字和下劃線
_
組成 - 不能以數字開頭
- 區分大小寫
- 不能是 Python 關鍵字(如
if
,for
,while
等)
命名慣例:
- 變量名:小寫字母,單詞間用下劃線
_
連接(如student_name
) - 常量名:全大寫字母(如
MAX_VALUE
) - 類名:首字母大寫的駝峰式(如
StudentInfo
) - 函數名:小寫字母,單詞間用下劃線(如
calculate_average
)
關鍵字
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
注意:
“False”,“None”,“True”首字母都需要大寫
Python 關鍵字詳解
二、變量與賦值 (Variables & Assignment)
變量定義:
Python中變量在訪問前,必須先綁定某個對象,即賦值,否則會報錯。
x = 10 # 整數
name = "Alice" # 字符串
is_valid = True # 布爾值
多重賦值:
a, b, c = 1, 2, 3 # 同時賦值多個變量
x = y = z = 0 # 多個變量賦相同值
變量交換:(很方便喲)
a, b = b, a # 交換兩個變量的值
注意:
- 使用換行符分隔,一般一行一條語句
- 從第一列開始,前面不能有空格,否則會出現語法錯誤
- “#”后為注釋語句
a = 100
b = "21"
a + bTypeError: unsupported operand type(s) for +: 'int' and 'str'
- Python是一種強類型語言,只支持該類型允許的運算操作
- a 指向整數類型對象,b指向字符串類型對象,整數類型數據和字符串類型數據不能接相加,即字符串類型數據不能自動轉換為整數類型數據。
三、輸入與輸出 (Input & Output)
輸入:
name = input("請輸入你的名字:") # 獲取字符串輸入
age = int(input("請輸入你的年齡:")) # 獲取整數輸入
輸出:
print("Hello World") # 基本輸出
print("Name:", name, "Age:", age) # 多個參數
print(f"Name: {name}, Age: {age}") # f-string (Python 3.6+)
注意:
- input()函數語句只能得到文本(字符串)
- eval()函數語句可以得到數字(輸入“ABC”等無法轉化為數字進行運算,會報錯……)
- Python中存在強制轉換 int(),float()
- sep:用來設定以什么字符間隔輸出對象,默認為空格
- end:用來設定以什么字符作為輸出對象的結尾,默認換行符“\n”,也可以是其他字符
Python中的eval()函數詳解
print('2025','5','5',sep='/')
print("the answer is ",end="") #使用end="",輸出字符串不會換行
print(3+4)
運行結果:
2025/5/5
the answer is 7
四、數值 (Numbers)
數值類型:
- 整數 (int):
10
,-5
,0
- 浮點數 (float):
3.14
,-0.001
,2.0
- 復數 (complex):
1+2j
數值運算:
# 基本運算
a = 10 + 3 # 加
b = 10 - 3 # 減
c = 10 * 3 # 乘
d = 10 / 3 # 除(返回浮點數)
e = 10 // 3 # 整除
f = 10 % 3 # 取余
g = 10 ** 3 # 冪運算# 增強賦值
x += 1 # 等價于 x = x + 1
Python中的數值運算函數及math庫詳解
五、字符串 (Strings)
字符串定義:
s1 = '單引號字符串'
s2 = "雙引號字符串"
s3 = """多行
字符串"""
字符串操作:
# 連接
full_name = first_name + " " + last_name# 重復
line = "-" * 20# 索引
first_char = s[0] # 第一個字符
last_char = s[-1] # 最后一個字符# 切片
sub = s[2:5] # 第3到第5個字符
every_second = s[::2] # 每隔一個字符# 常用方法
s.upper() # 轉為大寫
s.lower() # 轉為小寫
s.strip() # 去除兩端空白
s.split(",") # 按分隔符分割
s.replace("a", "b") # 替換字符
字符串格式化:
# 傳統方式
"Name: %s, Age: %d" % ("Alice", 20)# str.format()
"Name: {}, Age: {}".format("Alice", 20)# f-string (Python 3.6+)
f"Name: {name}, Age: {age}"
常用字符串函數
1. 基本操作函數
# 長度計算
s = "Hello"
len(s) # 返回5# 大小寫轉換
s.upper() # "HELLO"
s.lower() # "hello"
s.capitalize() # "Hello" 將字符串的首字母大寫
s.title() # "Hello" (對于多單詞字符串會每個單詞首字母大寫)# 查找和替換
s.find('e') # 1 (返回首次出現的索引,找不到返回-1)
s.rfind('l') # 3 返回該字符串在字符串s中最后的位置,不存在返回 -1
s.index('e') # 1 (類似find 但找不到會拋出異常:substring not found)
s.rindex('i') # 3 返回該字符串在字符串s中最后的位置
s.count('l') # 2 返回一個字符串在另一個字符串中出現的次數,不存在則結果為 0
s.replace('l', 'L') # "HeLLo"# 去除空白字符 (不修改原字符串)
" hello ".strip() # "hello" 移除字符串 開頭,結尾 的指定字符。默認移除空白字符(包括空格、制表符 \t、換行符 \n 等)。
" hello ".lstrip() # "hello "僅移除字符串 開頭 的指定字符。
" hello ".rstrip() # " hello"僅移除字符串 結尾 的指定字符。
補充鏈接:
Python中的strip()
Python中字符串分隔與連接函數
2. 判斷類函數
s.isalpha() # 是否全是字母
s.isdigit() # 是否全是數字
s.isalnum() # 是否字母或數字
s.isspace() # 是否全是空白字符
s.startswith('He') # True
s.endswith('lo') # True
3. 分割和連接
# 分割
"a,b,c".split(',') # ['a', 'b', 'c']
"a b c".split() # ['a', 'b', 'c'] (默認按空白字符分割)
"a\nb\nc".splitlines() # ['a', 'b', 'c']# 連接
'-'.join(['a', 'b', 'c']) # "a-b-c"
4. 格式化函數
# 舊式格式化
"Hello, %s!" % "world" # "Hello, world!"# str.format()
"Hello, {}!".format("world") # "Hello, world!"# f-string (Python 3.6+)
name = "world"
f"Hello, {name}!" # "Hello, world!"
字符串應用實例
1. 數據清洗
# 清理用戶輸入
user_input = " Some User Input "
cleaned = user_input.strip().lower()
print(cleaned) # "some user input"
2. 密碼強度檢查
def check_password(password):if len(password) < 8:return "密碼太短"if not any(c.isupper() for c in password):return "需要至少一個大寫字母"if not any(c.islower() for c in password):return "需要至少一個小寫字母"if not any(c.isdigit() for c in password):return "需要至少一個數字"return "密碼強度足夠"
3. 文本分析
text = "Python is an amazing programming language. Python is versatile."# 統計單詞出現次數
words = text.lower().split()
word_count = {}
for word in words:word = word.strip('.,!?') # 去除標點word_count[word] = word_count.get(word, 0) + 1print(word_count) # {'python': 2, 'is': 2, 'an': 1, ...}
4. 字符串加密
# 簡單的凱撒密碼
def caesar_cipher(text, shift):result = ""for char in text:if char.isupper():result += chr((ord(char) + shift - 65) % 26 + 65)elif char.islower():result += chr((ord(char) + shift - 97) % 26 + 97)else:result += charreturn resultencrypted = caesar_cipher("Hello, World!", 3)
print(encrypted) # "Khoor, Zruog!"
5. URL處理
# 解析查詢參數
url = "https://example.com/search?q=python&page=2"def parse_query(url):query = url.split('?', 1)[1]params = query.split('&')return {p.split('=')[0]: p.split('=')[1] for p in params}print(parse_query(url)) # {'q': 'python', 'page': '2'}
高級字符串操作
1. 正則表達式 (re模塊)
import re# 驗證電子郵件格式
def is_valid_email(email):pattern = r'^[\w\.-]+@[\w\.-]+\.\w+$'return re.match(pattern, email) is not Noneprint(is_valid_email("test@example.com")) # True
2. 字符串模板 (string.Template)
from string import Templatet = Template('Hello, $name!')
print(t.substitute(name='World')) # "Hello, World!"
3. 字符串對齊
s = "Python"
s.ljust(10) # 'Python '
s.rjust(10) # ' Python'
s.center(10) # ' Python '
類型轉換
Python 類型轉換詳解
資源庫
Python Turtle 入門繪圖庫
🐳 🐋 🐬