欢迎访问宙启技术站
智能推送

Python中lower()函数实现的字符串小写转换方法

发布时间:2023-12-28 08:26:26

lower()函数是Python字符串对象的内置方法,它用于将字符串中的大写字母转换为小写字母。下面是一个使用lower()函数实现字符串小写转换的例子:

# 示例一:将字符串全部转换为小写字母
string = "Hello World!"
lower_case = string.lower()
print(lower_case)
# 输出:hello world!

# 示例二:只转换字符串中的大写字母,其余字符保持不变
string = "HeLlo WOrld!"
lower_case = ""
for char in string:
    if char.isupper():  # 判断字符是否为大写字母
        lower_case += char.lower()  # 将大写字母转换为小写字母
    else:
        lower_case += char
print(lower_case)
# 输出:hello world!

在上述例子中,我们首先使用lower()函数将字符串全部转换为小写字母。在示例一中,字符串"Hello World!"中的所有字符"H"、"e"、"l"、"l"、"o"、" "、"W"、"o"、"r"、"l"、"d"都被转换为小写字母。输出结果为"hello world!"。

在示例二中,我们使用lower()函数将字符串中的大写字母转换为小写字母,而其他字符保持不变。对于字符串"HeLlo WOrld!",我们遍历每个字符,并使用isupper()函数判断字符是否为大写字母。如果是大写字母,则使用lower()函数将其转换为小写字母;否则,保持原样。最后得到的字符串为"hello world!"。