一、基礎入門知識
1.1 代碼規范
1.1.1 語句分隔符
;
- 換行
1.1.2 格式化
- 對 Windows 和 Linux 操作系統,快捷鍵是
Ctrl + Alt + L
- 對 macOS 操作系統,快捷鍵是
Cmd + Option + L
1.1.3 注釋
- 單行注釋
# 這是一行注釋
- 多行注釋
"""
這
是
多
行
注
釋
"""
1.1.4 官方文檔
PEP 8 – Style Guide for Python Code
1.2 變量
1.2.1 定義
- 變量是一個存儲數據值的容器
- 數據值可以是數字、字符串、列表、元組、字典、集合、布爾值等
1.2.2 變量名
- 變量名可以是任意的,但需要遵循規范
- 變量名規范:
- 可以是數字、字母、下劃線_
- 不允許是數字開頭
- 不允許是關鍵字或者內置函數等
- 建議是“小駝峰”結構或者下劃線分隔
1.2.3 變量值
- 變量是容器,數值是可以進行修改的
二、基本數據類型
2.1 數字類型
2.1.1 常見類型
- 整型
x = 10
print(x)
print(type(x))
- 浮點型
x = 3.14
print(x)
print(type(x))
2.1.2 代碼實操——計算圓形的周長和面積
"""
計算圓形的周長和面積
"""# 1. 工具包
import math# 2. 輸入圓的半徑
radius = 3# 3. 計算周長 + 面積
circumference = 2 * math.pi * radius
area = math.pi * radius**2print(f"圓形的周長:{circumference:.2f}")
print(f"圓形的面積:{area:.2f}")
- 結果運行圖:
2.2 布爾類型
2.2.1 常見類型
- True 真
- False 假
2.2.2 應用場景
- 在條件語句中,控制程序的流程
- 在邏輯運算中,表示結果的真假
2.2.3 與其他數據類型的轉換
- 在特定的上下文中,一些數據類型(如整型、浮點型、字符串等)可以被解釋為布爾值。
- 空值(如空列表、空字典、空字符串、0、None等)一般被看作是 False,而非空值一般被看作是 True。
2.2.4 代碼實操——邏輯運算
"""
邏輯運算
"""# 1. and運算
print(True and True)
print(True and False)# 2. or運算
print(True or False)
print(False or False)# 3. not運算
print(not True)
print(not False)
- 運行結果:
2.3 字符串類型
2.3.1 常見類型
- 單引號
' '
- 雙引號
" "
- 三引號
""" """
2.3.2 轉義符
- 定義:在字符串中,插入的無法直接表示或具有特殊含義的字符
- 常見類型:
\\
:用于在字符串中插入反斜杠\'
:用于在單引號字符串中插入單引號\"
:在雙引號字符串中插入雙引號\n
:用于在字符串中換行\t
:用于在字符串中插入制表符
2.3.3 格式化輸出
- 目的:將變量或表達式的結果嵌入到字符串中,以生成有意義的輸出。
- 常見類型:
%s
,%d
,%f
str.format()
f-string
2.3.4 序列操作
- 創建、修改、查找和格式化字符串
- 通過索引獲取字符
- 通過切片獲取字符
- 拼接字符串
- 計算機字符串長度
- 判斷某個字符或子字符串是否存在
2.3.5 內置方法
下面是優化后的字符串內置方法表格,增加了參數說明和示例,并保持排版清晰:
字符串內置方法詳解
方法 | 含義 | 參數 | 返回值 | 示例代碼 |
---|---|---|---|---|
upper() | 轉換為大寫 | 無 | 新字符串 | print("hello".upper()) → HELLO |
lower() | 轉換為小寫 | 無 | 新字符串 | print("WORLD".lower()) → world |
title() | 轉換為標題格式 | 無 | 新字符串 | print("hello world".title()) → Hello World |
startswith(prefix) | 是否以指定前綴開頭 | prefix : 前綴字符串 | 布爾值 | print("hello".startswith("he")) → True |
endswith(suffix) | 是否以指定后綴結尾 | suffix : 后綴字符串 | 布爾值 | print("hello".endswith("lo")) → True |
isdigit() | 是否全為數字字符 | 無 | 布爾值 | print("123".isdigit()) → True |
isalpha() | 是否全為字母字符 | 無 | 布爾值 | print("abc".isalpha()) → True |
isalnum() | 是否全為字母或數字 | 無 | 布爾值 | print("abc123".isalnum()) → True |
strip([chars]) | 去除兩邊指定字符 | chars : 要去除的字符集合 | 新字符串 | print(" hello ".strip()) → hello |
lstrip([chars]) | 去除左邊指定字符 | chars : 要去除的字符集合 | 新字符串 | print(" hello".lstrip()) → hello |
rstrip([chars]) | 去除右邊指定字符 | chars : 要去除的字符集合 | 新字符串 | print("hello ".rstrip()) → hello |
join(iterable) | 連接可迭代對象 | iterable : 包含字符串的可迭代對象 | 新字符串 | print("-".join(["a", "b", "c"])) → a-b-c |
split(sep=None) | 按分隔符分割字符串 | sep : 分隔符,默認為空白字符 | 字符串列表 | print("a,b,c".split(",")) → ['a', 'b', 'c'] |
find(sub) | 查找子字符串首次出現位置 | sub : 要查找的子字符串 | 索引或-1 | print("hello".find("l")) → 2 |
index(sub) | 查找子字符串首次出現位置 | sub : 要查找的子字符串 | 索引或報錯 | print("hello".index("l")) → 2 |
count(sub) | 統計子字符串出現次數 | sub : 要統計的子字符串 | 整數 | print("hello".count("l")) → 2 |
replace(old, new) | 替換指定子字符串 | old : 原字符串new : 新字符串 | 新字符串 | print("hello".replace("l", "L")) → heLLo |
center(width, fillchar) | 字符串居中填充 | width : 總寬度fillchar : 填充字符 | 新字符串 | print("hello".center(10, '*')) → **hello*** |
zfill(width) | 左側補零到指定寬度 | width : 總寬度 | 新字符串 | print("42".zfill(5)) → 00042 |
2.3.6 代碼實操
(1)創建字符串
"""
創建字符串
"""# 1. 單引號
name = '李白'
print(f'姓名:{name}')# 2. 雙引號
age = "18"
print(f"年齡:{age}")# 3. 三引號
hobby = """
1. movie
2. music
"""
print(f'興趣:{hobby}')
- 運行結果:
(2)插入轉義符
"""
插入轉義符
"""# 1. \'
string_1 = '老師:\'論文寫完了嘛?\''
print(string_1)# 2. \"
string_2 = "學生:\"快了,快了。\""
print(string_2)# 3. \n + \t
string_3 = "老師:\n\t\"速度!速度!\""
print(string_3)
- 運行結果
(3)格式化輸出
"""
格式化輸出
"""# 1. %s,%d,%f
name_1 = '李白'
age_1 = 18
print("我的名字是:%s,我的年齡是:%d歲。" % (name_1, age_1))# 2. str.format()
name_2 = '杜甫'
age_2 = 20
print("你的名字是:{},你的年齡是:{}歲。".format(name_2, age_2))# 3. f-string
name_3 = '蘇軾'
age_3 = 22
print(f"他的名字是:{name_3},他的年齡是:{age_3}歲。")
- 運行結果:
(4)序列操作
"""
序列操作
"""# 1. 創建字符串
str1 = "Hello"
str2 = 'World'
str3 = """
Hello
World
"""
print(f"str1:{str1}")
print(f"str2:{str2}")
print(f"str3:{str3}")print('--'*50)# 2. 通過索引獲取字符
print(f"第一個字符:{str1[0]}")
print(f"最后一個字符:{str1[-1]}")print('--'*50)# 3. 通過切片獲取字符
# 取首略尾
print(f"取首略尾:{str1[1:3]}")
# 默認到尾
print(f"默認到尾:{str1[1:]}")
# 從頭開始
print(f"從頭開始:{str1[:4]}")
# 從左向右
print(f"從左向右:{str1[1:4:1]}")
# 隔1取1
print(f"隔1取1:{str1[1:4:2]}")
# 反向截取
print(f"反向截取:{str1[3:1:-1]}")print('--'*50)# 4. 拼接字符串
concat1 = str1 + " " + str2
concat2 = "".join([str1, " ", str2])
print(f"concat1:{concat1}")
print(f"contact:{concat2}")print('--'*50)# 5. 計算字符串長度
print(f"str1的長度:{len(str1)}")
print(f"str3的行數:{len(str3.splitlines())}")print('--'*50)# 6. 判斷某個字符或子字符串是否存在
print(f"存在判斷: 'e' 在 {str1} 中: {'e' in str1}")
print(f"子串判斷: 'lo' 在 {str1} 中: {str1.find('lo') != -1}")
- 運行結果:
微語錄:被貼上標簽的人,只能等待著自己應得的人生。——《信》