iT邦幫忙

2024 iThome 鐵人賽

DAY 13
0
Python

一起來用 Snakify 練練手系列 第 13

【一起來用 Snakify 練練手】Day13 Lesson 5 練習題參考解答

  • 分享至 

  • xImage
  •  

Lesson5 單元的題目就像在玩邏輯一樣
東切西切然後組合起來

  • Slices
    😈 這一題一定要搞懂,後面都是應用
t = input()
print(t[2])
print(t[-2])
print(t[:5])
print(t[:-2])
print(t[::2])
print(t[1::2])
print(t[::-1])
print(t[::-2])
print(len(t))
  • The number of words
    😈 分割有很多種方式,看是要分割文字還是計算空格都行
t = input()
print(len(t.split(" ")))
  • The two halves
    😈 這一題是要將文字分成兩部分前後顛倒,要計算好位置喔
t = input()
print(t[(len(t) + 1) // 2:] + t[:(len(t) + 1) // 2])
  • To swap the two words
t = input()
print(t.split(" ")[1], t.split(" ")[0])
  • The first and last occurrence
t = input()
if t.count('f')>1:
    print(t.find('f'), t.rfind('f'))
elif t.count('f')==1:
    print(t.find('f'))
else:
    print('')
  • The second occurrence
t = input()

if t.count('f')==0:
    print(-2)
elif t.count('f')==1:
    print(-1)
else:
    print(t.find('f', t.find('f')+1))
  • Remove the fragment
t = input()
print(t[:t.find('h')]+t[t.rfind('h')+1:len(t)+1])
  • Reverse the fragment
    😈 這一題也是想好你要轉換的位置
t = input()
t1 = t[t.find('h'):t.rfind('h')+1]
print(t[:t.find('h')]+t1[::-1]+t[t.rfind('h')+1:len(t)+1])
  • Replace the substring
t = input()
print(t.replace('1', 'one'))
  • Delete a character
t = input()
print(t.replace('@', ""))
  • Replace within the fragment
    😈 這一題不難,但需要想清楚位置,可以先畫出來在寫,利用find()rfind()完成
t = input()
print(t[:t.find('h')+1]+t[t.find('h')+1:t.rfind('h')].replace("h", "H")+t[t.rfind('h'):])
  • Delete every third character
    😈 這裡可以想一下之前的餘數,要判斷條件來刪除不要的文字
t = input()
o = ''
for i in range(len(t)):
    if i%3!=0:
        o += t[i]
        
print(o)

上一篇
【一起來用 Snakify 練練手】Day12 Lesson 5 概念
下一篇
【一起來用 Snakify 練練手】Day14 Lesson 6 概念
系列文
一起來用 Snakify 練練手21
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言