如何使用Python函数来将字符串中的大小写转换?
发布时间:2023-07-02 12:32:55
在Python中,有几种方法可以将字符串中的大小写进行转换。以下是一些常用的方法:
1. 使用内置函数str.upper()和str.lower():str.upper()将字符串中的所有字符转换为大写,str.lower()将字符串中的所有字符转换为小写。示例如下:
text = "Hello World!" new_text1 = text.upper() # 输出:HELLO WORLD! new_text2 = text.lower() # 输出:hello world!
2. 使用字符串方法str.swapcase():str.swapcase()方法将字符串中的大写字符转换为小写,小写字符转换为大写。示例如下:
text = "Hello World!" new_text = text.swapcase() # 输出:hELLO wORLD!
3. 使用字符串方法str.title():str.title()方法将字符串中的每个单词的首字母转换为大写,其他字母转换为小写。示例如下:
text = "hello world!" new_text = text.title() # 输出:Hello World!
4. 使用内置函数str.capitalize():str.capitalize()函数将字符串中的 个字母转换为大写,其他字母转换为小写。示例如下:
text = "hello world!" new_text = text.capitalize() # 输出:Hello world!
5. 使用字符串方法str.casefold():str.casefold()方法将字符串中的字符转换为小写,并将一些特殊字符转换为对应的小写替代字符。示例如下:
text = "hElLo WOrld!" new_text = text.casefold() # 输出:hello world!
6. 使用函数str.maketrans()和str.translate():str.maketrans()函数创建一个字符映射转换表,str.translate()函数根据转换表将字符串中的字符进行转换。示例如下:
text = "Hello World!"
trans_table = str.maketrans('ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')
new_text = text.translate(trans_table) # 输出:hello world!
注意:以上方法中,原始字符串并没有改变,而是生成了一个新的字符串。如果想要保存转换后的字符串,需要将新字符串赋值给一个变量。
