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

如何使用Python函数将字符串中的字母大小写进行转换

发布时间:2023-07-04 16:57:47

Python提供了多个函数用于转换字符串中字母的大小写。下面将介绍其中的几个常用函数。

1. upper(): 将字符串中的所有字母转换为大写。

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

2. lower(): 将字符串中的所有字母转换为小写。

str = "Helloworld"
print(str.lower())  # 输出: helloworld

3. swapcase(): 将字符串中的大写字母转换为小写字母,小写字母转换为大写字母。

str = "Hello World"
print(str.swapcase())  # 输出: hELLO wORLD

4. capitalize(): 将字符串中的第一个字母转换为大写,其余字母转换为小写。

str = "hello world"
print(str.capitalize())  # 输出: Hello world

5. title(): 将字符串中的每个单词的第一个字母转换为大写,其余字母转换为小写。

str = "hello world"
print(str.title())  # 输出: Hello World

6. casefold(): 将字符串中的所有字母转换为小写,适用于不区分大小写的比较。

str = "HelLo WorlD"
print(str.casefold())  # 输出: hello world

7. isupper(): 判断字符串中的所有字母是否都是大写字母,返回布尔值。

str = "HELLO"
print(str.isupper())  # 输出: True

8. islower(): 判断字符串中的所有字母是否都是小写字母,返回布尔值。

str = "hello"
print(str.islower())  # 输出: True

以上是常用的字符串大小写转换函数,通过使用它们可以方便地进行字符串大小写的转换操作。