租用问题

质量为本、客户为根、勇于拼搏、务实创新

< 返回租用问题列表

python字母大小写转换的有哪些方法,python字母大小写转换代码怎么写的

发布时间:2023-09-27 15:24:34

python字母大小写转换的有哪些方法

Python中可使用内置的字符串方法来实现字母大小写转换。以下是几种经常使用的方法:

  1. 使用upper()方法将字符串中所有字母转换为大写字母:
string = "hello"
new_string = string.upper()
print(new_string)  # 输出 "HELLO"
  1. 使用lower()方法将字符串中所有字母转换为小写字母:
string = "WORLD"
new_string = string.lower()
print(new_string)  # 输出 "world"
  1. 使用capitalize()方法将字符串的首字母转换为大写字母,其余字母转换为小写字母:
string = "hello world"
new_string = string.capitalize()
print(new_string)  # 输出 "Hello world"
  1. 使用swapcase()方法将字符串中的大写字母转换为小写字母,小写字母转换为大写字母:
string = "Hello World"
new_string = string.swapcase()
print(new_string)  # 输出 "hELLO wORLD"

以上方法都会返回一个新的字符串,原始字符串不会被修改。如果需要在原字符串上进行修改,可以将新字符串赋值给原字符串变量。