在 Python 中,可以使用内置的字符串方法来转换大小写字母。下面是一些常用的方法:

  1. upper() 方法将字符串中的所有字母转换为大写字母。
string = "Hello, World!"
print(string.upper())  # 输出: HELLO, WORLD!
  1. lower() 方法将字符串中的所有字母转换为小写字母。
string = "Hello, World!"
print(string.lower())  # 输出: hello, world!
  1. capitalize() 方法将字符串的首字母转换为大写字母,其他字母转换为小写字母。
string = "hello, world!"
print(string.capitalize())  # 输出: Hello, world!
  1. title() 方法将字符串中的每个单词的首字母转换为大写字母,其他字母转换为小写字母。
string = "hello, world!"
print(string.title())  # 输出: Hello, World!
  1. swapcase() 方法将字符串中的大写字母转换为小写字母,小写字母转换为大写字母。
string = "Hello, World!"
print(string.swapcase())  # 输出: hELLO, wORLD!

注意:这些方法都返回一个新的字符串,不会修改原始字符串。如果想要修改原始字符串,可以将转换后的字符串赋值给原始字符串变量。

Python 字符串大小写转换方法:upper(), lower(), capitalize(), title(), swapcase()

原文地址: https://www.cveoy.top/t/topic/pUn1 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录