Python 程式從非空字串中移除第 n 個索引字元


當需要從非空字串中移除一個特定索引字元時,可以遍歷該字串,當索引不匹配時,該字元可以儲存在另一個字串中。

以下是相同內容的演示 -

示例

 動態演示

my_string = "Hi there how are you"

print("The string is :")
print(my_string)
index_removed = 2

changed_string = ''

for char in range(0, len(my_string)):
   if(char != index_removed):
      changed_string += my_string[char]

print("The string after removing ", index_removed, "nd character is : ")
print(changed_string)

輸出

The string is :
Hi there how are you
The string after removing 2 nd character is :
Hithere how are you

說明

  • 定義一個字串並將其顯示在控制檯上。

  • 定義一個索引值。

  • 遍歷該字串,如果字串中的字元與需要移除的索引值不同,則該字元將放置在一個新字串中。

  • 此新字串將在控制檯上顯示為輸出。

更新於:2021 年 4 月 17 日

662 次瀏覽

開啟 你的 職業生涯

完成該課程以獲得認證

開始
廣告
© . All rights reserved.