如何使用Python函数来将字符串转换为大写?
发布时间:2023-07-03 07:33:05
在Python中,可以使用字符串的内置方法upper()将字符串转换为大写。upper()方法返回一个新的字符串,其中所有的字母都被转换为大写形式。
下面是几种使用Python函数将字符串转换为大写的方法:
方法一:使用upper()方法
s = "hello world" s_upper = s.upper() print(s_upper) # 输出:HELLO WORLD
方法二:使用str的upper()函数
s = "hello world" s_upper = str.upper(s) print(s_upper) # 输出:HELLO WORLD
方法三:自定义函数将字符串转换为大写
def to_uppercase(string):
result = ""
for char in string:
if 'a' <= char <= 'z': # 判断是否为小写字母
char = chr(ord(char) - 32) # 转换为大写字母
result += char
return result
s = "hello world"
s_upper = to_uppercase(s)
print(s_upper) # 输出:HELLO WORLD
方法四:使用列表推导式
s = "hello world" s_upper = ''.join([char.upper() for char in s]) print(s_upper) # 输出:HELLO WORLD
方法五:使用map函数结合lambda表达式
s = "hello world" s_upper = ''.join(map(lambda char: char.upper(), s)) print(s_upper) # 输出:HELLO WORLD
无论使用哪种方法,都可以将字符串转换为大写,选择适合自己的方法即可。注意,这些方法都是将字符串的每个字符转换为大写形式,而不是只转换字符串的首字母。
