Re: [問題] 如何能做到字母進位呢?

看板Python作者 (恩歪批居)時間10年前發表 (2014/12/12 06:36), 10年前編輯推噓0(000)
留言0則, 0人參與, 最新討論串10/14 (看更多)
想到說如果用「字串 <-> 數字」完全轉換會有一個缺點, 要是字串很長,需要進位的情況又不多,那麼就有些浪費 以下是我的小小嘗試 大小寫保持原位,多進位出來的大小寫跟著原本的最高位 def alphaPlusOne(s): char_list = list(s) # start from least significant position for idx, c in enumerate(reversed(char_list)): if not isCarryAfterPlusOne(c): # no carry, + 1 and break char_list[idx] = chr(ord(c) + 1) break else: # carry, + 1 - 26 char_list[idx] = chr(ord(c) + 1 -26) if idx is 0: # still need carry at most significant position char_list.insert(0, chr(ord(c) + 1 -26)) return ''.join(char_list) def isCarryAfterPlusOne(c): return c is 'z' or c is 'Z' -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 210.61.165.30 ※ 文章網址: http://www.ptt.cc/bbs/Python/M.1418366169.A.59B.html ※ 編輯: nypgand1 (210.61.165.30), 12/12/2014 14:43:14
文章代碼(AID): #1KYepPMR (Python)
討論串 (同標題文章)
文章代碼(AID): #1KYepPMR (Python)