深度阅读

How to convert a string to uppercase or lowercase in Python?

作者
作者
2023年08月22日
更新时间
12.82 分钟
阅读时间
0
阅读量

Yes, there are indeed methods to convert a string to uppercase or lowercase in Python.

To convert a string to uppercase, you can use the upper() method. The upper() method returns a new string where all characters are converted to uppercase.

Here’s an example:

my_string = "hello, world!"
new_string = my_string.upper()
print(new_string)

Output:

"HELLO, WORLD!"

In this example, we have defined a string with lowercase characters, and then we call the upper() method on the string to convert all the characters to uppercase.

Similarly, to convert a string to lowercase, you can use the lower() method. The lower() method returns a new string where all characters are converted to lowercase.

Here’s an example:

my_string = "Hello, World!"
new_string = my_string.lower()
print(new_string)

Output:

"hello, world!"

In this example, we have defined a string with uppercase and lowercase characters, and then we call the lower() method on the string to convert all the characters to lowercase.

Note that these methods create new strings and do not modify the original string. If you want to modify the original string, you can re-assign the result of the upper() or lower() method back to the original variable.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。