Re: [問題] 如何能做到字母進位呢?
看板Python作者bigpigbigpig (To littlepig with love)時間11年前 (2014/12/12 01:17)推噓1(1推 0噓 0→)留言1則, 1人參與討論串6/14 (看更多)
※ 引述《opengood5566 ( )》之銘言:
: 比如說進行加一: a變b, at變au, az變ba
: 請問有甚麼辦法可以做到這樣嗎?
: 感謝!
我寫的,有點醜:
letters = 'abcdefghijklmnopqrstuvwxyz'
next_letter = dict(zip(letters,letters[1:]+letters[:1]))
def increment(s):
rs = list(reversed(s.lower()))
for p, l in enumerate(rs):
rs[p] = next_letter[l]
if l != 'z': break
if p == len(rs)-1 and l == 'z': rs.append('a')
return ''.join(reversed(rs))
===========================================================
>>> increment('at')
'au'
>>> increment('k')
'l'
>>> increment('z')
'aa'
>>> increment('zzzz')
'aaaaa'
>>> increment('cz')
'da'
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 111.251.228.62
※ 文章網址: http://www.ptt.cc/bbs/Python/M.1418318246.A.614.html
※ 編輯: bigpigbigpig (111.251.228.62), 12/12/2014 01:19:04
※ 編輯: bigpigbigpig (111.251.228.62), 12/12/2014 02:27:18
推
12/12 08:25, , 1F
12/12 08:25, 1F
討論串 (同標題文章)
Python 近期熱門文章
PTT數位生活區 即時熱門文章