Python 字符串大小写转换:详解与示例
在 Python 中,您可以使用内置的字符串方法轻松地转换字符串的大小写。以下是一些常用的方法:
upper()方法将字符串中的所有字符转换为大写字母。例如:
string = 'Hello World'
print(string.upper()) # 输出: HELLO WORLD
lower()方法将字符串中的所有字符转换为小写字母。例如:
string = 'Hello World'
print(string.lower()) # 输出: hello world
capitalize()方法将字符串的第一个字符转换为大写字母,其余字符转换为小写字母。例如:
string = 'hello world'
print(string.capitalize()) # 输出: Hello world
swapcase()方法将字符串中的大写字母转换为小写字母,小写字母转换为大写字母。例如:
string = 'Hello World'
print(string.swapcase()) # 输出: hELLO wORLD
title()方法将字符串中的每个单词的首字母转换为大写字母。例如:
string = 'hello world'
print(string.title()) # 输出: Hello World
需要注意的是,上述方法返回的是转换后的新字符串,原始字符串并不会被改变。如果想要改变原始字符串,可以将转换后的结果重新赋值给原始字符串变量。
原文地址: https://www.cveoy.top/t/topic/qvp0 著作权归作者所有。请勿转载和采集!