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.