Python中用于转换字符串大小写的函数是什么?
发布时间:2023-07-23 20:31:40
在Python中,我们可以使用以下函数来转换字符串的大小写:
1. upper(): 该函数将字符串中的所有字母都转换为大写形式,并返回新的字符串。例如:
string = "hello world" new_string = string.upper() print(new_string) # 输出: HELLO WORLD
2. lower(): 该函数将字符串中的所有字母都转换为小写形式,并返回新的字符串。例如:
string = "HELLO WORLD" new_string = string.lower() print(new_string) # 输出: hello world
3. capitalize(): 该函数将字符串的 个字母转换为大写形式,其余字母转换为小写形式,并返回新的字符串。例如:
string = "hello world" new_string = string.capitalize() print(new_string) # 输出: Hello world
4. title(): 该函数将字符串中的每个单词的首字母都转换为大写形式,并返回新的字符串。例如:
string = "hello world" new_string = string.title() print(new_string) # 输出: Hello World
5. swapcase(): 该函数将字符串中的大写字母转换为小写形式,小写字母转换为大写形式,并返回新的字符串。例如:
string = "Hello World" new_string = string.swapcase() print(new_string) # 输出: hELLO wORLD
需要注意的是,上述函数只是对字符串进行临时的大小写转换,并没有改变原始字符串本身。如有需要,可以将转换后的结果赋值给新的字符串变量。
