快速学习Python函数,以转换字符串大小写
发布时间:2023-07-26 08:29:15
Python中可以使用字符串的内置方法以及标准库中的函数来转换字符串的大小写。下面将介绍几种常用的方法。
1. 使用字符串的内置方法:
- upper(): 将字符串中的所有字符转换为大写。
- lower(): 将字符串中的所有字符转换为小写。
- capitalize(): 将字符串的首字母转换为大写,其余字符转换为小写。
- swapcase(): 将字符串中的大写字母转换为小写,小写字母转换为大写。
示例代码:
# 将字符串转换为大写 string = "hello world" print(string.upper()) # 输出: HELLO WORLD # 将字符串转换为小写 string = "Hello World" print(string.lower()) # 输出: hello world # 转换字符串的首字母为大写,其余字符为小写 string = "hello World" print(string.capitalize()) # 输出: Hello world # 大小写互换 string = "Hello World" print(string.swapcase()) # 输出: hELLO wORLD
2. 使用标准库中的函数:
- str.upper(string): 和字符串的upper()方法相同,将字符串中的所有字符转换为大写。
- str.lower(string): 和字符串的lower()方法相同,将字符串中的所有字符转换为小写。
- str.capitalize(string): 和字符串的capitalize()方法相同,将字符串的首字母转换为大写,其余字符转换为小写。
- str.swapcase(string): 和字符串的swapcase()方法相同,将字符串中的大写字母转换为小写,小写字母转换为大写。
示例代码:
# 将字符串转换为大写 import string string = "hello world" print(string.upper()) # 输出: HELLO WORLD # 将字符串转换为小写 import string string = "Hello World" print(string.lower()) # 输出: hello world # 转换字符串的首字母为大写,其余字符为小写 import string string = "hello World" print(string.capitalize()) # 输出: Hello world # 大小写互换 import string string = "Hello World" print(string.swapcase()) # 输出: hELLO wORLD
以上是常见的字符串大小写转换方法。通过掌握它们,可以轻松地转换字符串的大小写,从而满足不同的需求。
