Python 程式:刪除字串中奇數索引位置處的字元


當需要從字串的奇數索引中刪除字元時,會定義一個方法,以字串作為引數。

以下是相同內容的演示 −

示例

 即時演示

def remove_odd_index_characters(my_str):
   new_string = ""
   i = 0
   while i < len(my_str):
      if (i % 2 == 1):
         i+= 1
         continue

      new_string += my_str[i]
      i+= 1
   return new_string

if __name__ == '__main__':
   my_string = "Hi there Will"

   my_string = remove_odd_index_characters(my_string)
   print("Characters from odd index have been removed")
   print("The remaining characters are : ")
   print(my_string)

輸出

Characters from odd index have been removed
The remaining characters are :
H hr il

說明

  • 定義了一個名為“remove_odd_index_characters”的方法,它以字串作為引數。

  • 建立一個空字串。

  • 遍歷字串,將每個元素的索引除以 2.

  • 如果餘數不為 0,則將其視為奇數索引,並將其刪除。

  • 在主方法中,呼叫該方法,並定義字串。

  • 此字串作為引數傳遞給該方法。

  • 輸出顯示在控制檯上。

更新於:2021 年 4 月 16 日

572 次瀏覽

開啟你的職業生涯

完成課程並獲得認證

開始
廣告
© . All rights reserved.