HOW TO REMOVE A CHARACTER FROM STRING IN PYTHON
We know that String in Python is immutable. In this article we will show you some methods through which we can remove a character from a string
Method 1
s = "PythonPoint" print("Original string is: ",s) ch = int(input("Enter the position of character to be removed: ")) new = "" for i in range(len(s)): if i!=ch-1: new = new + s[i] print("Final string is: ",new)
Output:
Original string is: PythonPoint Enter the position of character to be removed: 1 Final string is: ythonPoint
Method 2: Using replace()
This method removes all the occurrences of the character from the string, that is if duplicate elements are present, those will be removed too.
s = "PythonPoint" print("Original string is: ",s) ch = input("Enter the character to be removed: ") new = s.replace(ch, '') print("Final string is: ",new)
Output:
Original string is: PythonPoint Enter the character to be removed: o Final string is: PythnPint
Method 3: Using slicing and concatenation
s = "PythonPoint" print("Original string is: ",s) ch = int(input("Enter the position of character to be removed: ")) new = s[:ch-1] + s[ch:] print("Final string is: ", new)
Output:
Original string is: PythonPoint Enter the position of character to be removed: 4 Final string is: PytonPoint
Subscribe
Login
Please login to comment
0 Discussion