内置函数
Python提供了丰富的内置函数,无需导入任何模块即可直接使用。以下是几个常用内置函数的详细介绍:
round() - 四舍五入
python
# 基本用法
print(round(3.14159)) # 输出: 3
print(round(3.14159, 2)) # 输出: 3.14
print(round(3.14159, 3)) # 输出: 3.142
# 处理银行家舍入法(四舍六入五成双)
print(round(2.5)) # 输出: 2
print(round(3.5)) # 输出: 4
max() 和 min() - 最大值与最小值
python
# 基本数值比较
numbers = [10, 5, 20, 15, 8]
print(max(numbers)) # 输出: 20
print(min(numbers)) # 输出: 5
# 字符串比较(按ASCII码)
words = ["apple", "banana", "cherry"]
print(max(words)) # 输出: "cherry"
print(min(words)) # 输出: "apple"
# 使用key参数自定义比较规则
students = [
{"name": "Alice", "score": 85},
{"name": "Bob", "score": 92},
{"name": "Charlie", "score": 78}
]
print(max(students, key=lambda x: x["score"])) # 输出: {'name': 'Bob', 'score': 92}
sorted() - 排序函数
python
# 基本排序
numbers = [3, 1, 4, 1, 5, 9, 2]
print(sorted(numbers)) # 输出: [1, 1, 2, 3, 4, 5, 9]
# 降序排序
print(sorted(numbers, reverse=True)) # 输出: [9, 5, 4, 3, 2, 1, 1]
# 自定义排序规则
words = ["apple", "Banana", "cherry", "date"]
print(sorted(words)) # 输出: ['Banana', 'apple', 'cherry', 'date']
print(sorted(words, key=str.lower)) # 输出: ['apple', 'Banana', 'cherry', 'date']
# 对字典按值排序
scores = {"Alice": 85, "Bob": 92, "Charlie": 78}
sorted_scores = sorted(scores.items(), key=lambda x: x[1], reverse=True)
print(sorted_scores) # 输出: [('Bob', 92), ('Alice', 85), ('Charlie', 78)]
int 和 float 的运算符
算术运算符
python
# 基本算术运算
a = 10
b = 3
print(a + b) # 加法: 13
print(a - b) # 减法: 7
print(a * b) # 乘法: 30
print(a / b) # 除法: 3.3333333333333335
print(a // b) # 整除: 3
print(a % b) # 取模: 1
print(a ** b) # 幂运算: 1000
取模运算符 % 的详细用法
python
# 1. 基本取余运算
print(10 % 3) # 输出: 1
print(15 % 4) # 输出: 3
print(7 % 2) # 输出: 1(判断奇偶性)
# 2. 负数取模
print(-10 % 3) # 输出: 2(Python中结果总是正数)
print(10 % -3) # 输出: -2
# 3. 浮点数取模
print(10.5 % 3) # 输出: 1.5
print(7.8 % 2.5) # 输出: 0.2999999999999998
# 4. 实际应用场景
# 判断闰年
year = 2024
if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
print(f"{year}年是闰年")
# 循环队列索引计算
queue_size = 5
current_index = 3
next_index = (current_index + 1) % queue_size # 输出: 4
prev_index = (current_index - 1) % queue_size # 输出: 2
# 时间转换
total_seconds = 3665
hours = total_seconds // 3600
minutes = (total_seconds % 3600) // 60
seconds = total_seconds % 60
print(f"{hours}:{minutes}:{seconds}") # 输出: 1:1:5
比较运算符
python
a = 10.5
b = 10
print(a == b) # 等于: False
print(a != b) # 不等于: True
print(a > b) # 大于: True
print(a < b) # 小于: False
print(a >= b) # 大于等于: True
print(a <= b) # 小于等于: False
赋值运算符
python
x = 10
x += 5 # x = x + 5
x -= 3 # x = x - 3
x *= 2 # x = x * 2
x /= 4 # x = x / 4
x //= 2 # x = x // 2
x %= 3 # x = x % 3
x **= 2 # x = x ** 2
str类的方法
join() 方法详解
python
# 1. 基本用法:将列表连接成字符串
words = ["Hello", "World", "Python"]
result = " ".join(words)
print(result) # 输出: "Hello World Python"
# 2. 使用不同分隔符
numbers = ["1", "2", "3", "4", "5"]
print(",".join(numbers)) # 输出: "1,2,3,4,5"
print("-".join(numbers)) # 输出: "1-2-3-4-5"
print("".join(numbers)) # 输出: "12345"
print("\n".join(numbers)) # 输出: 每行一个数字
# 3. 连接元组
tuple_data = ("apple", "banana", "cherry")
print(" and ".join(tuple_data)) # 输出: "apple and banana and cherry"
# 4. 连接集合(顺序可能不同)
set_data = {"a", "b", "c"}
print("|".join(set_data)) # 输出可能是: "a|b|c" 或 "b|c|a" 等
# 5. 连接字典(默认连接键)
dict_data = {"name": "Alice", "age": "25", "city": "Beijing"}
print(";".join(dict_data)) # 输出: "name;age;city"
# 6. 实际应用场景
# 构建SQL查询条件
conditions = ["status = 'active'", "age > 18", "city = 'Beijing'"]
sql_where = " AND ".join(conditions)
print(f"WHERE {sql_where}")
# 构建文件路径
path_parts = ["home", "user", "documents", "file.txt"]
file_path = "/".join(path_parts)
print(file_path) # 输出: "home/user/documents/file.txt"
# 构建CSV行
data_row = ["Alice", "25", "Beijing", "Engineer"]
csv_line = ",".join(data_row)
print(csv_line) # 输出: "Alice,25,Beijing,Engineer"
其他常用字符串方法
python
text = " Hello, World! "
# 大小写转换
print(text.upper()) # 输出: " HELLO, WORLD! "
print(text.lower()) # 输出: " hello, world! "
print(text.title()) # 输出: " Hello, World! "
print(text.capitalize()) # 输出: " hello, world! "
# 去除空白字符
print(text.strip()) # 输出: "Hello, World!"
print(text.lstrip()) # 输出: "Hello, World! "
print(text.rstrip()) # 输出: " Hello, World!"
# 查找和替换
print(text.find("World")) # 输出: 9
print(text.replace("World", "Python")) # 输出: " Hello, Python! "
# 分割字符串
print(text.split(",")) # 输出: [' Hello', ' World! ']
print(text.split()) # 输出: ['Hello,', 'World!']
# 判断字符串特性
print("hello".isalpha()) # 输出: True
print("123".isdigit()) # 输出: True
print("hello123".isalnum()) # 输出: True
re正则表达式
正则表达式(Regular Expression)是处理字符串的强大工具,Python通过re模块提供正则表达式支持。以下是正则表达式的核心用法:
1. 基本匹配
python
import re
# 简单匹配
pattern = r"hello"
text = "hello world"
match = re.search(pattern, text)
if match:
print(f"找到匹配: {match.group()}") # 输出: 找到匹配: hello
# 匹配开头和结尾
text = "Python is awesome"
if re.match(r"^Python", text): # 匹配开头
print("以Python开头")
if re.search(r"awesome$", text): # 匹配结尾
print("以awesome结尾")
2. 常用元字符
python
import re
text = "我的电话是123-456-7890,邮箱是test@example.com"
# \d - 匹配数字
numbers = re.findall(r"\d+", text)
print(numbers) # 输出: ['123', '456', '7890']
# \w - 匹配单词字符(字母、数字、下划线)
words = re.findall(r"\w+", text)
print(words) # 输出: ['我的电话是123', '456', '7890', '邮箱是test', 'example', 'com']
# \s - 匹配空白字符
spaces = re.findall(r"\s", text)
print(f"空白字符数量: {len(spaces)}") # 输出: 空白字符数量: 6
# . - 匹配任意字符(除换行符)
any_char = re.findall(r".", "abc123")
print(any_char) # 输出: ['a', 'b', 'c', '1', '2', '3']
# [] - 字符集
vowels = re.findall(r"[aeiou]", "hello world")
print(vowels) # 输出: ['e', 'o', 'o']
# | - 或运算
matches = re.findall(r"电话|邮箱", text)
print(matches) # 输出: ['电话', '邮箱']
3. 量词
python
import re
# * - 0次或多次
print(re.findall(r"ab*", "a ab abb abbb")) # 输出: ['a', 'ab', 'abb', 'abbb']
# + - 1次或多次
print(re.findall(r"ab+", "a ab abb abbb")) # 输出: ['ab', 'abb', 'abbb']
# ? - 0次或1次
print(re.findall(r"ab?", "a ab abb abbb")) # 输出: ['a', 'ab', 'ab', 'ab']
# {n} - 恰好n次
print(re.findall(r"\d{3}", "123 4567 89012")) # 输出: ['123', '456', '890']
# {n,} - 至少n次
print(re.findall(r"\d{3,}", "123 4567 89012")) # 输出: ['123', '4567', '89012']
# {n,m} - n到m次
print(re.findall(r"\d{2,4}", "1 12 123 1234 12345")) # 输出: ['12', '123', '1234', '1234']
4. 分组和捕获
python
import re
# 简单分组
text = "2023-12-25"
match = re.match(r"(\d{4})-(\d{2})-(\d{2})", text)
if match:
print(f"完整匹配: {match.group()}") # 输出: 2023-12-25
print(f"年: {match.group(1)}") # 输出: 2023
print(f"月: {match.group(2)}") # 输出: 12
print(f"日: {match.group(3)}") # 输出: 25
print(f"所有分组: {match.groups()}") # 输出: ('2023', '12', '25')
# 命名分组
text = "姓名: 张三, 年龄: 25"
pattern = r"姓名: (?P<name>\w+), 年龄: (?P<age>\d+)"
match = re.search(pattern, text)
if match:
print(f"姓名: {match.group('name')}") # 输出: 张三
print(f"年龄: {match.group('age')}") # 输出: 25
5. 常用函数
python
import re
text = "apple 123 banana 456 cherry 789"
# findall - 查找所有匹配
all_numbers = re.findall(r"\d+", text)
print(all_numbers) # 输出: ['123', '456', '789']
# search - 查找第一个匹配
first_match = re.search(r"\d+", text)
if first_match:
print(f"第一个数字: {first_match.group()}") # 输出: 第一个数字: 123
# match - 从开头匹配
start_match = re.match(r"apple", text)
if start_match:
print("以apple开头") # 输出: 以apple开头
# split - 分割字符串
parts = re.split(r"\s+\d+\s+", text)
print(parts) # 输出: ['apple', 'banana', 'cherry 789']
# sub - 替换
new_text = re.sub(r"\d+", "NUM", text)
print(new_text) # 输出: apple NUM banana NUM cherry NUM
# subn - 替换并返回替换次数
new_text, count = re.subn(r"\d+", "NUM", text)
print(f"新文本: {new_text}") # 输出: 新文本: apple NUM banana NUM cherry NUM
print(f"替换次数: {count}") # 输出: 替换次数: 3
6. 实际应用示例
python
import re
# 1. 验证邮箱格式
def validate_email(email):
pattern = r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"
return bool(re.match(pattern, email))
emails = ["test@example.com", "invalid.email", "user@domain.co.uk"]
for email in emails:
print(f"{email}: {'有效' if validate_email(email) else '无效'}")
# 2. 提取手机号码
text = "联系方式:13800138000,备用:13912345678,无效:12345"
phones = re.findall(r"1[3-9]\d{9}", text)
print(f"找到手机号: {phones}") # 输出: 找到手机号: ['13800138000', '13912345678']
# 3. 清理HTML标签
html = "<div>Hello <b>World</b>!</div>"
clean_text = re.sub(r"<[^>]+>", "", html)
print(clean_text) # 输出: Hello World!
# 4. 提取URL
text = "访问 https://www.example.com 或 http://test.site/path"
urls = re.findall(r"https?://[^\s]+", text)
print(f"找到URL: {urls}") # 输出: 找到URL: ['https://www.example.com', 'http://test.site/path']
# 5. 密码强度验证
def check_password_strength(password):
if len(password) < 8:
return "弱: 密码太短"
if not re.search(r"[A-Z]", password):
return "中: 缺少大写字母"
if not re.search(r"[a-z]", password):
return "中: 缺少小写字母"
if not re.search(r"\d", password):
return "中: 缺少数字"
if not re.search(r"[!@#$%^&*]", password):
return "中: 缺少特殊字符"
return "强: 密码符合要求"
passwords = ["abc123", "Password123", "StrongP@ss123"]
for pwd in passwords:
print(f"{pwd}: {check_password_strength(pwd)}")
7. 编译正则表达式(提高性能)
python
import re
# 编译正则表达式(适合重复使用)
pattern = re.compile(r"\d{3}-\d{3}-\d{4}")
# 使用编译后的对象
texts = [
"电话: 123-456-7890",
"手机: 987-654-3210",
"无效: 12-34-56"
]
for text in texts:
match = pattern.search(text)
if match:
print(f"找到电话: {match.group()}")
else:
print("未找到有效电话")
8. 标志参数
python
import re
text = "Hello\nWORLD\npython"
# re.IGNORECASE (re.I) - 忽略大小写
matches = re.findall(r"python", text, re.IGNORECASE)
print(f"忽略大小写匹配: {matches}") # 输出: 忽略大小写匹配: ['python']
# re.MULTILINE (re.M) - 多行模式
matches = re.findall(r"^[A-Z]+", text, re.MULTILINE)
print(f"多行模式匹配: {matches}") # 输出: 多行模式匹配: ['H', 'WORLD']
# re.DOTALL (re.S) - 让.匹配换行符
matches = re.findall(r"Hello.*python", text, re.DOTALL)
print(f"DOTALL匹配: {matches}") # 输出: DOTALL匹配: ['Hello\nWORLD\npython']
# 组合使用多个标志
pattern = re.compile(r"^hello", re.IGNORECASE | re.MULTILINE)
matches = pattern.findall("Hello\nhello\nHELLO")
print(f"组合标志匹配: {matches}") # 输出: 组合标志匹配: ['Hello', 'hello', 'HELLO']
正则表达式是Python中处理文本的利器,掌握这些基础用法能极大提高字符串处理效率。
list(列表)
列表的基本操作
python
# 1. 创建列表
empty_list = []
numbers = [1, 2, 3, 4, 5]
mixed_list = [1, "hello", 3.14, True]
nested_list = [[1, 2], [3, 4], [5, 6]]
# 2. 访问元素
fruits = ["apple", "banana", "cherry", "date", "elderberry"]
print(fruits[0]) # 输出: "apple"
print(fruits[-1]) # 输出: "elderberry"
print(fruits[1:4]) # 输出: ["banana", "cherry", "date"]
print(fruits[:3]) # 输出: ["apple", "banana", "cherry"]
print(fruits[2:]) # 输出: ["cherry", "date", "elderberry"]
# 3. 修改列表
fruits[1] = "blueberry"
print(fruits) # 输出: ["apple", "blueberry", "cherry", "date", "elderberry"]
# 4. 添加元素
fruits.append("fig") # 末尾添加
fruits.insert(2, "grape") # 指定位置插入
print(fruits)
# 5. 删除元素
removed = fruits.pop() # 删除并返回最后一个元素
removed2 = fruits.pop(1) # 删除指定位置元素
fruits.remove("cherry") # 删除第一个匹配的元素
del fruits[0] # 删除指定位置元素
# 6. 列表方法
numbers = [3, 1, 4, 1, 5, 9, 2]
numbers.sort() # 原地排序
numbers.reverse() # 反转列表
count = numbers.count(1) # 统计元素出现次数
index = numbers.index(5) # 查找元素索引
# 7. 列表推导式
squares = [x**2 for x in range(10)]
even_squares = [x**2 for x in range(10) if x % 2 == 0]
# 8. 列表复制
original = [1, 2, 3]
shallow_copy = original.copy() # 浅拷贝
deep_copy = original[:] # 另一种浅拷贝方式
列表的常用操作
python
# 连接列表
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined = list1 + list2 # 输出: [1, 2, 3, 4, 5, 6]
extended = list1.copy()
extended.extend(list2) # 输出: [1, 2, 3, 4, 5, 6]
# 列表长度和检查
print(len([1, 2, 3])) # 输出: 3
print(2 in [1, 2, 3]) # 输出: True
print(4 not in [1, 2, 3]) # 输出: True
# 遍历列表
for index, fruit in enumerate(fruits):
print(f"索引 {index}: {fruit}")
# 列表解包
first, second, *rest = [1, 2, 3, 4, 5]
print(first) # 输出: 1
print(second) # 输出: 2
print(rest) # 输出: [3, 4, 5]
dict(字典)
字典的基本操作
python
# 1. 创建字典
empty_dict = {}
person = {"name": "Alice", "age": 25, "city": "Beijing"}
dict_from_keys = dict.fromkeys(["name", "age", "city"], "unknown")
# 2. 访问元素
print(person["name"]) # 输出: "Alice"
print(person.get("age")) # 输出: 25
print(person.get("country", "China")) # 输出: "China"(默认值)
# 3. 修改字典
person["age"] = 26 # 修改值
person["country"] = "China" # 添加新键值对
person.update({"job": "Engineer", "salary": 50000}) # 批量更新
# 4. 删除元素
del person["city"] # 删除键值对
age = person.pop("age") # 删除并返回值
person.clear() # 清空字典
# 5. 字典方法
person = {"name": "Alice", "age": 25, "city": "Beijing"}
keys = person.keys() # 所有键
values = person.values() # 所有值
items = person.items() # 所有键值对
# 6. 遍历字典
for key in person:
print(f"{key}: {person[key]}")
for key, value in person.items():
print(f"{key}: {value}")
# 7. 字典推导式
squares = {x: x**2 for x in range(5)} # 输出: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
# 8. 合并字典(Python 3.9+)
dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}
merged = dict1 | dict2 # 输出: {"a": 1, "b": 3, "c": 4}
字典的常用技巧
python
# 设置默认值
from collections import defaultdict
# 使用defaultdict
word_count = defaultdict(int)
for word in ["apple", "banana", "apple", "cherry", "banana", "apple"]:
word_count[word] += 1
print(dict(word_count)) # 输出: {'apple': 3, 'banana': 2, 'cherry': 1}
# 使用setdefault
data = {}
data.setdefault("key", []).append("value")
data.setdefault("key", []).append("another_value")
print(data) # 输出: {'key': ['value', 'another_value']}
# 字典排序
scores = {"Alice": 85, "Bob": 92, "Charlie": 78}
# 按键排序
sorted_by_key = dict(sorted(scores.items()))
# 按值排序
sorted_by_value = dict(sorted(scores.items(), key=lambda x: x[1]))
# 字典解包
def print_person(name, age, city):
print(f"{name} is {age} years old, living in {city}")
person = {"name": "Alice", "age": 25, "city": "Beijing"}
print_person(**person) # 输出: Alice is 25 years old, living in Beijing
int、float、str、list之间的转换函数
类型转换函数总览
python
# 1. int() - 转换为整数
print(int(3.14)) # 输出: 3(浮点数转整数,截断小数部分)
print(int("42")) # 输出: 42(字符串转整数)
print(int("1010", 2)) # 输出: 10(二进制字符串转十进制整数)
print(int(True)) # 输出: 1(布尔值转整数)
print(int(False)) # 输出: 0
# 2. float() - 转换为浮点数
print(float(42)) # 输出: 42.0
print(float("3.14")) # 输出: 3.14
print(float("1e-3")) # 输出: 0.001
print(float(True)) # 输出: 1.0
# 3. str() - 转换为字符串
print(str(42)) # 输出: "42"
print(str(3.14)) # 输出: "3.14"
print(str([1, 2, 3])) # 输出: "[1, 2, 3]"
print(str({"a": 1})) # 输出: "{'a': 1}"
print(str(True)) # 输出: "True"
# 4. list() - 转换为列表
print(list("hello")) # 输出: ['h', 'e', 'l', 'l', 'o']
print(list((1, 2, 3))) # 输出: [1, 2, 3](元组转列表)
print(list({"a": 1, "b": 2})) # 输出: ['a', 'b'](字典转列表,只保留键)
print(list(range(5))) # 输出: [0, 1, 2, 3, 4]
# 5. 列表转字符串的多种方法
my_list = ["apple", "banana", "cherry"]
# 方法1: join() - 最常用
result1 = ", ".join(my_list)
print(result1) # 输出: "apple, banana, cherry"
# 方法2: str() - 直接转换(保留列表格式)
result2 = str(my_list)
print(result2) # 输出: "['apple', 'banana', 'cherry']"
# 方法3: 列表推导式 + join
result3 = " | ".join([str(item) for item in my_list])
print(result3) # 输出: "apple | banana | cherry"
# 方法4: 使用map函数
result4 = " - ".join(map(str, my_list))
print(result4) # 输出: "apple - banana - cherry"
# 6. 字符串转列表的多种方法
my_string = "apple,banana,cherry"
# 方法1: split() - 按分隔符分割
result5 = my_string.split(",")
print(result5) # 输出: ['apple', 'banana', 'cherry']
# 方法2: 按空格分割
text = "hello world python"
result6 = text.split()
print(result6) # 输出: ['hello', 'world', 'python']
# 方法3: 使用列表推导式处理复杂字符串
complex_str = "a1,b2,c3,d4"
result7 = [item.upper() for item in complex_str.split(",")]
print(result7) # 输出: ['A1', 'B2', 'C3', 'D4']
# 方法4: 将字符串的每个字符转为列表
word = "hello"
result8 = list(word)
print(result8) # 输出: ['h', 'e', 'l', 'l', 'o']
# 方法5: 使用eval()转换字符串形式的列表(注意安全风险)
list_str = "[1, 2, 3, 4, 5]"
result9 = eval(list_str) # 仅用于受信任的输入
print(result9) # 输出: [1, 2, 3, 4, 5]
# 方法6: 使用ast.literal_eval()安全转换
import ast
list_str2 = '["apple", "banana", "cherry"]'
result10 = ast.literal_eval(list_str2)
print(result10) # 输出: ['apple', 'banana', 'cherry']
# 7. 实际应用示例
# CSV数据处理
csv_data = "Alice,25,Beijing,Engineer"
fields = csv_data.split(",")
print(f"姓名: {fields[0]}, 年龄: {fields[1]}, 城市: {fields[2]}, 职业: {fields[3]}")
# 配置文件解析
config_str = "host=localhost;port=8080;debug=true"
config_list = config_str.split(";")
config_dict = {}
for item in config_list:
key, value = item.split("=")
config_dict[key] = value
print(config_dict) # 输出: {'host': 'localhost', 'port': '8080', 'debug': 'true'}
# 单词统计
sentence = "Python is awesome and Python is powerful"
words = sentence.split()
word_count = {}
for word in words:
word_count[word] = word_count.get(word, 0) + 1
print(word_count) # 输出: {'Python': 2, 'is': 2, 'awesome': 1, 'and': 1, 'powerful': 1}