本文目录导读:

在Python中,字符串大小写转换有多种方法,以下是常用的几种:
全部转换
text = "Hello World 123" # 全部转大写 print(text.upper()) # 输出: HELLO WORLD 123 # 全部转小写 print(text.lower()) # 输出: hello world 123 # 大小写互换 print(text.swapcase()) # 输出: hELLO wORLD 123
首字母大写
text = "hello world" # 每个单词首字母大写(标题格式) print(text.title()) # 输出: Hello World # 仅字符串第一个字符大写 print(text.capitalize()) # 输出: Hello world
字符串开头/结尾判断
text = "Hello World" # 检查是否以大写字母开头 print(text[0].isupper()) # True # 检查是否全部大写 print(text.isupper()) # False # 检查是否全部小写 print(text.islower()) # False
实际应用示例
# 用户输入标准化
user_input = " Hello World "
clean_input = user_input.strip().lower()
print(clean_input) # 输出: hello world
# 比较忽略大小写
def case_insensitive_compare(str1, str2):
return str1.lower() == str2.lower()
print(case_insensitive_compare("Python", "PYTHON")) # True
# 转换文件名
filename = "My Document.PDF"
new_filename = filename.lower().replace(" ", "_")
print(new_filename) # 输出: my_document.pdf
特殊字符处理
# 中文字符不受大小写影响 chinese = "Python编程" print(chinese.upper()) # 输出: PYTHON编程 # 带数字和符号 mixed = "Hello_World_2023!" print(mixed.upper()) # 输出: HELLO_WORLD_2023!
注意事项:)` 方法会将每个单词首字母大写,包括冠词、介词等
capitalize()只将字符串的第一个字母大写- 非字母字符(数字、符号)不受大小写转换影响
- 中文字符没有大小写概念,转换后保持不变
选择合适的方法取决于你的具体需求,比如进行用户输入标准化、文本比较或格式化输出等。