如何使用python函数来将字符串全部转换为大写?
发布时间:2023-08-11 16:07:35
Python提供了内置函数upper(),可以将字符串转换为大写。下面是一些关于如何使用upper()函数的示例代码。
示例1:将字符串中的所有字符转换为大写字母。
string = "hello world" string = string.upper() print(string)
输出结果:
HELLO WORLD
示例2:使用函数将用户输入的字符串转换为大写。
def convert_to_uppercase(string):
return string.upper()
user_input = input("请输入字符串:")
converted_string = convert_to_uppercase(user_input)
print(converted_string)
输出结果:
请输入字符串:hello world HELLO WORLD
示例3:将字符串列表中的所有字符串转换为大写。
string_list = ["hello", "world", "python"] converted_list = [string.upper() for string in string_list] print(converted_list)
输出结果:
['HELLO', 'WORLD', 'PYTHON']
示例4:使用map()函数将字符串列表中的所有字符串转换为大写。
string_list = ["hello", "world", "python"] converted_list = list(map(str.upper, string_list)) print(converted_list)
输出结果:
['HELLO', 'WORLD', 'PYTHON']
示例5:将包含多个段落的字符串转换为大写,并保留段落结构。
string = "Hello!
This is a paragraph.
This is another paragraph."
paragraphs = string.split("
")
converted_paragraphs = [paragraph.upper() for paragraph in paragraphs]
converted_string = "
".join(converted_paragraphs)
print(converted_string)
输出结果:
HELLO! THIS IS A PARAGRAPH. THIS IS ANOTHER PARAGRAPH.
以上是几个示例,展示了如何使用Python函数将字符串全部转换为大写。根据实际需要,你可以在这些示例的基础上进行修改和拓展。
