Skip to main content
 首页 » 编程设计

与 s.upper 作用相同的 Python 函数

2025年05月04日21exmyth

因此,我正在尝试创建一个函数,以与 s.upper 相同的方式将字符串的所有字母大写,但采用函数的格式。我想尝试使用 ord() 和 chr() 但声明如果字符串的字符 >90 将其替换为比原始矿石少 32 的字符。我觉得我有一些片段,但我不确定如何将它们实际组合在一起。我知道我需要一个字符串累加器,但我不知道如何将它们组合在一起。到目前为止我有这个:

 def Uppercase(s): 
     x = '' 
     for ch in s: 
     x = -----> confused about what the accumulation would be 
     if ch ord() > 91: 
         s.replace(ch, chr(ord())-----> not sure that this is possible to implement 

请您参考如下方法:

如果一个字符的 ord() 值介于 97 和 122(包括两者)之间,那么您可以从中减去 32 以获得相应的大写字母。

使用 str.join 和 list comprehension 的单行代码:

>>> def upper_case(s): 
    return "".join([ chr(ord(x)-32) if 97<=ord(x)<=122 else x for x in s ]) 
 
>>> upper_case("foo bar") 
'FOO BAR' 

更具可读性的版本:

>>> def upper_case(s): 
    new_strs = [] 
    for char in s: 
        ordi = ord(char) 
        if 97 <= ordi <= 122: 
            new_strs .append( chr(ordi-32) ) 
        else:     
            new_strs.append(char) 
    return "".join(new_strs)     #join the list using str.join and return 
...  
>>> upper_case("foo bar") 
'FOO BAR' 
 
>>> from string import ascii_lowercase 
>>> upper_case(ascii_lowercase) 
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'