Program to remove ith character from the given string using Python

Introduction

In this section of python programming, our task is to remove the ith positioned character from the given string.

Program to remove ith character from the given string
NOTE: In the above example we removed the ith positioned character considering the indexing starts from 1. But in programming by default the indexing starts from 0.

 

Program

input_str = input("Please enter the string:\n")
input_pos = int(input("Enter the position:"))
output_str2 = ""


# USing slicing
output_str = input_str[:input_pos] + input_str[input_pos+1:]
print("Output using slicing : "+ output_str)


# Using str.join()
output_str1 = ''.join([input_str[i] for i in range(len(input_str)) if i != input_pos])
print("Output using str.join() and list comprehension : "+ output_str1)


# Using loop
for j in range(len(input_str)):
    if j != input_pos:
        output_str2 = output_str2 + input_str[j]
print("Output using loop : "+output_str2)

 

Output

Program to remove ith character from the given string Output

Explanation

In the above python code, we have used three ways to remove the character form ith position. The first one is using slicing and concatenation of strings. The statement “input_str[ : input_pos]”  (at line 7) will cut the strings from position 4 and statement “input_str[input_pos+1:]”  will cut the string after position 4. Using concatenation the strings are joined and displayed on the screen.

The second way is by using str.join() and list comprehension. The characters of the strings are converted to the elements of the list and the index is checked against the input_pos . By using “ ‘  ‘.join() “ the elements are again joined to form the strings except the element at position input_pos.

The third way we used is the loop. The variable j will loop till the length of input_str and check whether the value of j is equalled to input_pos. The characters are appended to the output_str except the character at index 3.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.