題目
針對(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ù)更新中……)