Python字符串大小写转换方法

高分请教下,Python字符串大小写转换方法
最新回答
替月亮关灯

2026-10-25 20:53:05

Python提供了多种字符串大小写转换的内置方法。首先,使用lower()函数可以将所有字符转换为小写,如将"Hello,Pvthon"进行转换,代码如下:

python
original_string = "Hello,Pvthon"
lower_case_string = original_string.lower()
print(lower_case_string) # 输出: hello,pvthon

其次,title()方法适用于创建标题样式字符串,首字母大写,其余字母小写,如将"hello.python"转换为标题式:

python
title_case_string = "hello.python".title()
print(title_case_string) # 输出: Hello.Python

而对于首字母大写,其余字母小写的需求,capitalize()函数可以实现,如:

python
capitalized_string = "hello.python".capitalize()
print(capitalized_string) # 输出: Hello.python

最后,swapcase()方法用于交换字符串中大写字母与小写字母,例如"HELLO,python"的转换:

python
swap_string = "HELLO,python".swapcase()
print(swap_string) # 输出: hello,Python

以上就是Python中对字符串大小写转换的几种常用方法及其应用实例。