Python系列:在Python字符串字母的大小写转换的4大方法
warning:
这篇文章距离上次修改已过197天,其中的内容可能已经有所变动。
在Python中,可以使用内置的字符串方法来进行字母的大小写转换。以下是4种常用的方法:
- 使用
str.lower()
将字符串转换为小写。 - 使用
str.upper()
将字符串转换为大写。 - 使用
str.capitalize()
将字符串中的首字母转换为大写,其余为小写。 - 使用
str.title()
将字符串中每个单词的首字母转换为大写,其余为小写。
示例代码:
original_string = "Hello World!"
# 转换为小写
lower_case = original_string.lower()
print(lower_case) # 输出: hello world!
# 转换为大写
upper_case = original_string.upper()
print(upper_case) # 输出: HELLO WORLD!
# 首字母大写,其余小写
capitalized = original_string.capitalize()
print(capitalized) # 输出: Hello world!
# 每个单词首字母大写,其余小写
title_case = original_string.title()
print(title_case) # 输出: Hello World!
评论已关闭