Python編程題6--字符串每隔3個(gè)字符翻轉(zhuǎn)

題目

針對(duì)一個(gè)只含數(shù)字的字符串,對(duì)其每3個(gè)數(shù)字進(jìn)行一次翻轉(zhuǎn),如下:

字符串:123456789 ==> 翻轉(zhuǎn)后:321654987

如果最后待翻轉(zhuǎn)的不足3個(gè)字符,也同樣進(jìn)行翻轉(zhuǎn),如下:

字符串:12345678 ==> 翻轉(zhuǎn)后:32165487

實(shí)現(xiàn)思路1

  • 遍歷字符串
  • 每間隔3個(gè)字符,對(duì)其進(jìn)行翻轉(zhuǎn),然后拼接到新字符串
  • 遍歷結(jié)束后,判斷新字符串的長度,是否和原字符串一致
  • 如果不一致則需要對(duì)剩余部分字符進(jìn)行翻轉(zhuǎn),再拼接到新字符串

代碼實(shí)現(xiàn)

def demo(s):
    new_str = ""
    for i in range(len(s)):
        if (i + 1) % 3 == 0:
            new_str += s[i-2:i+1][::-1]
    if len(s) != len(new_str):
        new_str += s[len(new_str):][::-1]
    return new_str

old_str = "12345678"
print(demo(old_str))

實(shí)現(xiàn)思路2

  • 遍歷字符串,步長為3
  • 準(zhǔn)備一個(gè)列表,每3個(gè)字符,作為一個(gè)字符串添加到列表中
  • 遍歷列表,對(duì)列表中的每個(gè)字符串進(jìn)行翻轉(zhuǎn),再通過 join() 方法用依次拼接

代碼實(shí)現(xiàn)

def demo(s):
    temp = []
    for i in range(0, len(s), 3):
        temp.append(s[i:i+3])
    return "".join([i[::-1] for i in temp])

old_str = "12345678"
print(demo(old_str))

兩行代碼實(shí)現(xiàn)

old_str = "12345678"
print("".join([old_str[i:i+3][::-1] for i in range(0, len(old_str), 3)]))

更多Python編程題,等你來挑戰(zhàn):Python編程題匯總(持續(xù)更新中……)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容