Python Program to Remove the nth Index Character from a Non-Empty String

PythonServer Side ProgrammingProgramming

When it is required to remove a specific index character from a string which isn’t empty, it can be iterated over, and when the index doesn’t match, that character can be stored in another string.

Below is the demonstration of the same −

Example

 Live Demo

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)

Output

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

Explanation

  • A string is defined, and is displayed on the console.

  • An index value is defined.

  • The string is iterated over, and if the character in the string is not same as the index value that needs to be removed, the character is placed in a new string.

  • This new string is displayed as output on the console.

raja
Published on 17-Apr-2021 15:23:00
Advertisements