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

Python中字符串大小写转换的函数方法

发布时间:2023-07-02 21:44:22

在Python中,可以使用以下函数和方法对字符串的大小写进行转换:

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

string = "Hello World"
lower_string = string.lower()
print(lower_string) # 输出: hello world

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

string = "Hello World"
upper_string = string.upper()
print(upper_string) # 输出: HELLO WORLD

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

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

4. title():将字符串中的每个单词的首字母转换为大写。

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

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

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

6. casefold():将字符串中的所有字符转换为小写,并处理一些特殊的unicode字符。

string = "HéllO W?rld"
casefolded_string = string.casefold()
print(casefolded_string) # 输出: héll? w?rld

需要注意的是,字符串是不可变对象,这意味着这些方法并不会改变原始字符串,而是返回一个新的字符串。如果你想改变原始字符串,可以将结果重新赋值给原始字符串的变量。

string = "Hello World"
string = string.lower()
print(string) # 输出: hello world

除了使用这些方法外,还可以使用format()函数来更改字符串的大小写。

string = "Hello World"
lower_string = "{}".format(string.lower())
print(lower_string) # 输出: hello world

这是一些可以在Python中使用的将字符串大小写转换的函数和方法,根据你的需求选择适合的方法即可。