lower()`函数将字符串转换为小写
发布时间:2023-06-14 09:16:22
lower() 函数是 Python 中内置的字符串函数,它的作用是将一个字符串的所有字母转换为小写,返回一个新的字符串。该函数的使用方法为:str.lower(),其中 str 是需要转换为小写的字符串。
下面是一些示例,展示了 lower() 函数的使用方法和效果。
string = "Hello, World!" lowercase_string = string.lower() print(string) # Hello, World! print(lowercase_string) # hello, world!
从上面的代码可以看出,该函数并不会改变原字符串的大小写,而是会返回一个新的字符串,其中所有字母都被转换成小写字母。
另外,lower() 函数还可以结合其它字符串函数一起使用,实现更为复杂的字符串操作。例如,下面的代码使用 lower() 函数和 strip() 函数将字符串中的空格和换行符去除,并将字母都转换为小写,然后输出结果。
string = " HeLLo,
\tWorLd! "
cleaned_string = string.strip().lower()
print(string) # HeLLo,
# WorLd!
print(cleaned_string) # hello,world!
从上面的代码可以看出,字符串函数可以被链式调用,以实现更为复杂的操作。在上面的示例中,我们先使用 strip() 函数去除了字符串中的空格和换行符,然后再使用 lower() 函数将字符串中所有字母转换为小写字母。最后,输出结果为 hello,world!。
需要注意的是,lower() 函数只能将字符串中的字母转换为小写字母,并不能影响数字、标点符号等其它字符。如果需要将整个字符串转换为小写,可以使用 lower() 函数和 replace() 函数组合使用,如下所示:
string = "Hello, World! 123"
lowercase_string = string.lower().replace(" ", "")
print(string) # Hello, World! 123
print(lowercase_string) # hello,world!123
在上面的示例中,我们先使用 lower() 函数将所有字母转换为小写,然后再使用 replace() 函数将空格替换为空字符串。最终得到的 hello,world!123 是整个字符串的小写版本。
