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

如何使用Python函数将字符串转换为大写或小写?

发布时间:2023-09-07 06:34:20

在Python中,可以使用内置函数upper()lower()来将字符串转换为大写和小写。

upper()函数将字符串中的所有字母转换为大写形式,并返回一个新的字符串。例如:

s = "hello world"
new_s = s.upper()
print(new_s)  # 输出: HELLO WORLD

lower()函数将字符串中的所有字母转换为小写形式,并返回一个新的字符串。例如:

s = "HELLO WORLD"
new_s = s.lower()
print(new_s)  # 输出: hello world

这两个函数可以用于任何字符串,无论是由变量存储的字符串还是直接写在代码中的字符串。它们也可以与字符串方法链式使用。例如:

s = "Hello World"
new_s = s.upper().lower()
print(new_s)  # 输出: hello world

此外,upper()lower()函数不会改变原始字符串的内容,而是返回一个新的字符串。如果想要改变原始字符串的内容,可以将结果赋值给原始字符串变量。例如:

s = "hello world"
s = s.upper()  # 将大写字符串赋值给变量,改变原始字符串的内容
print(s)  # 输出: HELLO WORLD

s = "HELLO WORLD"
s = s.lower()  # 将小写字符串赋值给变量,改变原始字符串的内容
print(s)  # 输出: hello world

综上所述,可以使用upper()lower()函数将字符串转换为大写或小写形式,并在需要时将结果赋值给变量。这两个函数在处理字符串时非常方便和实用。