Python 如何将字符串中的所有大写字母转换为小写
字符串是一组字符,可以用来表示单个单词或整个短语。在Python中使用字符串非常简单,因为它们不需要显式声明,可以带有或不带有指定符定义。Python具有各种内置函数和方法用于操作和访问字符串。因为Python中的所有内容都是对象,字符串是String类的对象,该类具有几个方法。
在本文中,我们重点介绍如何将每个大写字母转换为小写字母的方法。
使用lower()方法
通过使用字符串库的内置方法 lower() ,我们可以将所有大写字母转换为小写字母。该方法不考虑字符是大写还是小写,将字符串中的所有字符都转换为小写。它不需要任何参数进行调整,只是将当前字符串转换为小写。
示例1
在下面的示例中,我们输入一个字符串,并使用 lower() 方法将其转换为小写。
str1 = "WELCOME TO TUTORIALSPOint"
print("Converting the string to lowercase")
print(str1.lower())
输出
上述程序的输出是:
Converting the string to lowercase
welcome to tutorialspoint
示例2
在下面给出的程序中,我们将一个字符串作为输入,并逐个字符检查它是小写字母还是大写字母,然后改变其大小写并将其添加到一个新字符串中。
str1 ='WELCOME TO Tutorialspoint'
lowerString =''
for a in str1:
if (a.isupper()) == True:
lowerString += (a.lower())
else:
lowerString += a
print("The lowercase of the given string is")
print(lowerString)
输出
上述程序的输出是,
The lowercase of the given string is
welcome to tutorialspoint
示例3
在下面的示例中,我们获取输入的符号、数字和字符组合并将其转换为小写。
str1 = "HYDERABAD@1234"
print("Converting the string to lowercase")
print(str1.lower())
输出
上述程序的输出为,
Converting the string to lowercase
hyderabad@1234
示例4
在下面给出的示例中,我们接收一串符号、数字和字符的输入,并使用isupper()方法将其转换为小写。
str1 ='HYDERABAD@1234'
lowerString =''
for a in str1:
if (a.isupper()) == True:
lowerString += (a.lower())
else:
lowerString += a
print("The lowercase of the given string is")
print(lowerString)
输出
以上程序的输出为:
The lowercase of the given string is
hyderabad@1234