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

Python中如何将字符串转换为大写

发布时间:2023-12-18 05:08:02

在Python中,可以使用字符串的upper()方法来将字符串转换为大写。

以下是使用例子:

# 单个字符串转换为大写
string = "hello world"
upper_string = string.upper()
print(upper_string)  # 输出: HELLO WORLD

# 使用列表推导式将列表中的所有字符串转换为大写
strings = ["hello", "world"]
upper_strings = [s.upper() for s in strings]
print(upper_strings)  # 输出: ['HELLO', 'WORLD']

# 使用for循环将列表中的所有字符串转换为大写
strings = ["hello", "world"]
upper_strings = []
for s in strings:
    upper_strings.append(s.upper())
print(upper_strings)  # 输出: ['HELLO', 'WORLD']

# 使用map函数将列表中的所有字符串转换为大写
strings = ["hello", "world"]
upper_strings = list(map(str.upper, strings))
print(upper_strings)  # 输出: ['HELLO', 'WORLD']

# 使用生成器表达式将文件中的所有行转换为大写
file_path = "example.txt"
with open(file_path, "r") as file:
    upper_lines = (line.upper() for line in file)
    for upper_line in upper_lines:
        print(upper_line)

更多关于字符串的操作可以参考Python官方文档:https://docs.python.org/3/library/stdtypes.html#string-methods