Python program for removing n-th character from a string?

ProgrammingPythonServer Side Programming

In this article, we will remove the nth character from a string in Python. Let’s say we have the following input string −

Amitdiwan

The output should be the following after removing nth character i.e. 2nd index −

Amt

Python program for removing n-th character from a string

In this example, we will remove the nth character from a string −

Example

def removechar(str1, n): x = str1[ : n] y = str1[n + 1: ] return x + y # Driver Code if __name__ == '__main__': str1 = input("Enter a String =") n = int(input("Enter the n-th index =")) print("The new string =
"
) print(removechar(str1, n))

Output

Enter a String= Jacob
Enter the n-th index = 2
The new string =
Jaob

Python program for removing n-th character from a string without user input

In this example, we will remove the nth character from a string without user input −

Example

def removechar(myStr, n): x = myStr[ : n] y = myStr[n + 1: ] return x + y # Driver Code if __name__ == '__main__': myStr = "Hello" print("String = ",myStr) # nth index # character to be removed at this index n = 2 print("The new string = ",removechar(myStr, n))

Output

String = Hello
The new string = Helo

Python program for removing n-th character from a string using for loop

In this example, we will remove the nth character from a string using for loop −

Example

# Create a String myStr = "How are you?" # Display the initial string print("String = ",myStr) # nth index # The character is to be removed at this index n = 9 newStr = '' # for loop iteration for char in range(0, len(myStr)): if(char != n): # append newStr += myStr[char] # Display the updated string print("Updated string = ",newStr)

Output

String = How are you?
Updated string = How are yu?
raja
Updated on 11-Aug-2022 10:03:48

Advertisements