大小写问题
538 語
3 分
大小写问题
以下是 Python 中大小写规则的核心应用范例,涵盖命名规范与字符串处理两大场景:
一、命名规范(PEP 8 标准)
| 类型 | 规范 | 范例 | 说明 |
|---|---|---|---|
| 变量 / 函数 | 小写 + 下划线 | user_name, get_data() | 区分可读性 |
| 类名 | 大驼峰(PascalCase) | UserAccount, HttpRequest | 首字母大写,无下划线 |
| 常量 | 全大写 + 下划线 | MAX_SIZE, PI | 模块级常量 |
| 私有成员 | 前导单下划线 | _internal_var | 约定俗成,非强制 |
| 强私有 | 前导双下划线 | __private_attr | 触发名称改写(name mangling) |
| 魔术方法 | 前后双下划线 | __init__, __str__ | 系统保留,大小写敏感 |
# 变量与函数:snake_casedef calculate_area(radius): return 3.14 * radius ** 2
# 类名:PascalCaseclass CircleShape: def __init__(self, radius): self.radius = radius
# 常量:全大写PI = 3.14159MAX_RETRY = 5
# 大小写敏感:以下三者完全不同count = 1Count = 2COUNT = 3print(count, Count, COUNT) # 1 2 3二、字符串大小写处理
text = "Hello Python"
# 1. 全转大写 / 小写print(text.upper()) # HELLO PYTHONprint(text.lower()) # hello python
# 2. 首字母大写(句首)print("abc".capitalize()) # Abc
# 3. 每个单词首字母大写(标题化)print(text.title()) # Hello Pythonprint("hello-world".title()) # Hello-World(注意连字符后的 w)
# 4. 大小写互换print("AbCd".swapcase()) # aBcD
# 5. 大小写不敏感比较email1 = "User@Example.COM"email2 = "user@example.com"print(email1.lower() == email2.lower()) # True
# 6. 判断方法(返回布尔值)print("abc".islower()) # Trueprint("ABC".isupper()) # Trueprint("Hello World".istitle()) # Trueprint("123".isupper()) # False(无字母时返回 False)三、关键注意点
-
关键字大小写严格
# 正确if True:pass# 错误:True 不能写成 true(与 JavaScript 不同)if true: # SyntaxError -
模块与包名
import os # 标准库全小写import sysfrom datetime import datetime # 模块小写,类名大驼峰 -
路径与系统交互(Windows 除外)
# Linux/macOS 文件名区分大小写open("Data.txt") # 与 "data.txt" 是不同的文件
四、实用场景:用户输入规范化
def confirm_action(): choice = input("确认删除?(yes/no): ").strip().lower() if choice in ("yes", "y"): print("已删除") elif choice in ("no", "n"): print("已取消") else: print("输入无效")
confirm_action()核心原则:Python 是完全大小写敏感的语言,命名时遵循 PEP 8 规范能大幅提升代码的可读性和协作效率。
記事を共有
この記事が役に立ったなら、ぜひ他の人と共有してください!
関連記事スマート
1
README
开发与编程🧠mindcraft⛏️ Crafting minds for Minecraft with LLMs and Mineflayer! FAQ | Discord Support | Video Tutorial | Blog Post…
2
README
开发与编程Use this service to connect your bot to an unsupported minecraft server versions. Run: After first start it will create…
3
running_human_ai
开发与编程Human AI Instructions Finishing Installation Install the conda environment for running the experiments by executing this…
4
音乐解析引擎还有动作捕捉数据集怎么获取?
开发与编程音乐解析引擎和动作捕捉数据集的获取,可以分为"现成开源资源直接调用"和"需要自研/申请的核心模块"两类。以下是可直接落地的获取路径: 一、音乐解析引擎:获取与实现 1.1 现成开源库(立即可用) 这些库覆盖了除 PRE 以外的所有基础音频分…
5
README_ConstructionTasks
开发与编程Construction Tasks Generation Overview Instructions on how to customize construction task generation. Getting Started Ed…
ランダム記事ランダム
















