python3 字符串大小写转换

本文介绍了如何使用Python内置方法进行字符串大小写转换,包括全转大写、全转小写、首字母大写及每词首字母大写,是Python初学者掌握字符串操作的实用指南。

以下代码演示了如何将字符串转换为大写字母,或者将字符串转为小写字母等:

# Filename : test.py
# author by : www.runoob.com

str = "www.runoob.com"
print(str.upper())          # 把所有字符中的小写字母转换成大写字母
print(str.lower())          # 把所有字符中的大写字母转换成小写字母
print(str.capitalize())     # 把第一个字母转化为大写字母,其余小写
print(str.title())          # 把每个单词的第一个字母转化为大写,其余小写

执行以上代码输出结果为:

WWW.RUNOOB.COM
www.runoob.com
Www.runoob.com
Www.Runoob.Com

 

Python中,字符串大小写转换是一个常见的操作,通常可以通过内置的方法实现。以下是几种常用的字符串大小写转换方法: ### 使用 `lower()` 方法 该方法将字符串中的所有大写字母转换为小写字母。例如: ```python text = "HELLO WORLD" lower_text = text.lower() print(lower_text) # 输出: hello world ``` ### 使用 `upper()` 方法 该方法将字符串中的所有小写字母转换为大写字母。例如: ```python text = "hello world" upper_text = text.upper(); print(upper_text) # 输出: HELLO WORLD ``` ### 使用 `capitalize()` 方法 该方法将字符串的第一个字母转换为大写字母,其余字母转换为小写字母。例如: ```python text = "hello world" capitalized_text = text.capitalize(); print(capitalized_text) # 输出: Hello world ``` ### 使用 `title()` 方法 该方法将每个单词的首字母转换为大写字母,其余字母转换为小写字母。例如: ```python text = "hello world" title_text = text.title(); print(title_text) # 输出: Hello World ``` ### 使用自定义字典映射 对于更复杂的转换需求,可以创建一个包含大小写字母映射的字典来实现特定的转换逻辑。例如: ```python def custom_case(text, mapping): return ''.join(mapping.get(c, c) for c in text) # 创建大小写映射字典 lower_to_upper = {chr(i): chr(i).upper() for i in range(97, 123)} upper_to_lower = {chr(i): chr(i).lower() for i in range(65, 91)} mapping = {**lower_to_upper, **upper_to_lower} text = "Hello World" converted_text = custom_case(text, mapping) print(converted_text) # 输出: hELLO wORLD ``` 以上方法提供了不同的字符串大小写转换方式,可以根据具体需求选择合适的方法[^1]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值