大小写问题

538 words
3 minutes
大小写问题

以下是 Python 中大小写规则的核心应用范例,涵盖命名规范与字符串处理两大场景:


一、命名规范(PEP 8 标准)#

类型规范范例说明
变量 / 函数小写 + 下划线user_name, get_data()区分可读性
类名大驼峰(PascalCase)UserAccount, HttpRequest首字母大写,无下划线
常量全大写 + 下划线MAX_SIZE, PI模块级常量
私有成员前导单下划线_internal_var约定俗成,非强制
强私有前导双下划线__private_attr触发名称改写(name mangling)
魔术方法前后双下划线__init__, __str__系统保留,大小写敏感
# 变量与函数:snake_case
def calculate_area(radius):
return 3.14 * radius ** 2
# 类名:PascalCase
class CircleShape:
def __init__(self, radius):
self.radius = radius
# 常量:全大写
PI = 3.14159
MAX_RETRY = 5
# 大小写敏感:以下三者完全不同
count = 1
Count = 2
COUNT = 3
print(count, Count, COUNT) # 1 2 3

二、字符串大小写处理#

text = "Hello Python"
# 1. 全转大写 / 小写
print(text.upper()) # HELLO PYTHON
print(text.lower()) # hello python
# 2. 首字母大写(句首)
print("abc".capitalize()) # Abc
# 3. 每个单词首字母大写(标题化)
print(text.title()) # Hello Python
print("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()) # True
print("ABC".isupper()) # True
print("Hello World".istitle()) # True
print("123".isupper()) # False(无字母时返回 False)

三、关键注意点#

  1. 关键字大小写严格

    # 正确
    if True:
    pass
    # 错误:True 不能写成 true(与 JavaScript 不同)
    if true: # SyntaxError
  2. 模块与包名

    import os # 标准库全小写
    import sys
    from datetime import datetime # 模块小写,类名大驼峰
  3. 路径与系统交互(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 规范能大幅提升代码的可读性和协作效率。

Share Article

If this article helped you, please share it with others!

大小写问题
https://boyuan.net.cn/en/posts/大小写问题/
Author
Boyuan
Published at
2026-05-26

Comments

Profile Image of the Author
Boyuan
石以砥焉,化钝为利。
欢迎来访
石以砥焉,化钝为利。这里是我的个人站点,主要记录学习笔记、项目实践和一些零散的想法。站内文章可用右上角搜索,也可以订阅 RSS。
Categories
Tags
Latest Moments
Site Statistics
Posts
139
Categories
17
Tags
49
Total Words
1,721,112
Running Days
0 days
Last Activity
0 days ago
Site Info
Build Platform
Local
Blog Version
v1.0.0
License
CC BY-NC-SA 4.0
Table of Contents