1. 程式人生 > >對字串首字母大寫的改進

對字串首字母大寫的改進

前面寫的那個雖然也可實現將首字母小寫變為大寫的功能,但首字母如果本身是大寫,就會出錯,下面這個進行改進
def huan(str1):
    len1=len(str1);
    for i in range(len1):
        if(i==0):
            if(ord(str1[i])>=65 and ord(str1[i])<=90):
                print(str1[i],end='');
            else:
                print(chr(ord(str1[0])-32),end='');
        else:
            if(str1[i-1]==' '):
                 if(ord(str1[i])>=65 and ord(str1[i])<=90):
                      print(str1[i],end='');
                 else:
                      print(chr(ord(str1[i]) - 32), end='');
            else:
                 print(str1[i],end='');
str1=input('輸入');
huan(str1);