In this tutorial, I will show you different ways for how to remove character from string in python. So without wasting any time let’s get started.
1. Remove Character By Using Replace Method
In this code example, we used the replace() method of string to substitute characters from it.
# replace character from string in python >>> x = "abbaacccfag" # input string # Remove all 'a' from the string with empty string >>> x.replace("a","") 'bbcccfg' # remove newline from string python >>> "test \n 123 \n 456".replace("\n","") 'test 123 456'
Set the count argument to remove only specific number of times.
>>> x = "abbaacccfag" # input string # only remove first occuring 'a' >>> x.replace("a","",1) 'bbaacccfag' # only remove 2 a >>> 'bbacccfag'
Also read about how to remove spaces from string in python
2. Remove Character From String In Python By Using For Loop
In the below coding snippet, we used for loop to remove all characters from the string.
Here is the algorithm.
- First, we define an empty string.
- Then we iterate through each character of the input string.
- On each iteration, we check if the current character is not equal to the character to be removed, then add it to the string.
- Return the final string to the user.
def remove(string,element): """ Function to Remove Character From String In Python """ result = '' # define an empty string for i in string: # iterate through the string if i!= element: # if i is not equal element result += i # add to the string return result x = "abbaacccfag" print(remove(x,"a"))
Here is the output of above code.
That’s wrap for this tutorial.