Python字符串大小写转换方法
在Python字符串字母的大小写转换的4大方法
1、使用`lower()`方法,把所有大写字母转换成小写字母。
2、使用`upper()`方法,把所有小写字母转换成大写字母
3、使用`capitalize()`方法,仅首字母转化为大写字母,其余小写字母
4、使用`title()`方法,把每个单词的首字母转化为大写字母,其余为小写字母
常用大小写转换方法
1. lower()方法
将字符串中的所有大写字符转换为小写
text = "Hello WORLD"
result = text.lower()
print(result) # 输出: hello world
2. upper()方法
将字符串中的所有小写字符转换为大写
text = "Hello World"
result = text.upper()
print(result) # 输出: HELLO WORLD
3. capitalize()方法
将字符串的首字母大写,其余字母小写
text = "hello WORLD"
result = text.capitalize()
print(result) # 输出: Hello world
4. title()方法
将字符串中每个单词的首字母大写
text = "hello world of python"
result = text.title()
print(result) # 输出: Hello World Of Python
5. swapcase()方法
将字符串中的大小写互换
text = "Hello World"
result = text.swapcase()
print(result) # 输出: hELLO wORLD
实际应用场景
用户输入规范化
username = input("请输入用户名: ").lower()
# 统一转换为小写,避免大小写敏感问题
print(f"标准化的用户名: {username}")
数据清洗
raw_data = ["Apple", "apple", "APPLE", "aPpLe"]
cleaned_data = [item.lower() for item in raw_data]
print(cleaned_data) # 输出: ['apple', 'apple', 'apple', 'apple']
标题格式处理
article_title = "introduction to python programming"
formatted_title = article_title.title()
print(formatted_title) # 输出: Introduction To Python Programming
方法对比
|
方法 |
功能 |
返回值 |
原字符串是否改变 |
|---|---|---|---|
|
lower() |
全部转换为小写 |
新字符串 |
否 |
|
upper() |
全部转换为大写 |
新字符串 |
否 |
|
capitalize() |
首字母大写,其余小写 |
新字符串 |
否 |
|
title() |
每个单词首字母大写 |
新字符串 |
否 |
|
swapcase() |
大小写互换 |
新字符串 |
否 |
注意事项
- Python字符串是不可变对象,所有大小写转换方法都返回新的字符串
title()方法可能对带有撇号的单词处理不当(如"it's"会被转换为"It'S")- 某些语言有特定的大小写转换规则,需要特别注意
- 比较字符串时最好先统一大小写:
if input_str.lower() == "yes": - 大小写转换不影响非字母字符

浙公网安备 33010602011771号