In this tutorial we would like to show you how to remove a specific character from a string using Python.
We have many techniques to remove a character from the string. Today, we’ll cover the following cases: removing the first, last, and any specific characters from the provided character / word strings alongside with the corresponding Python 3 code examples.
Remove the first character in the string
Using the extended slicing technique, we can slice off the first character from the string. Let’s look at an example.
def removefirstcharacter(value): finalstring = value[1:] return finalstring mystring = 'imy python string' print("String:",mystring) print("Final string:",removefirstcharacter(mystring))
String: imy python string Final string: my python string
Removing the last character
The Extended slicing technique has the feature to slice the last character in the string. We will need to make only one change from our previous code.
def removelastcharacter(value): finalstring = value[:-1] return finalstring mystring = 'my python stringg' print("String:",mystring) print("Final string:",removelastcharacter(mystring))
String: my python stringg Final string: my python string
Remove any specific character
To remove a specific character using an index value, we will convert the string to a list and remove the index value by pop() function. We will use the join() function to change it back to a string datatype.
def removecharacter(name,index): mylist = list(name) mylist.pop(index) mystring = ''.join(mylist) return mystring getstring = input("Enter a string: ") char_index = int(input("Enter the index position to remove: ")) print("Index no",char_index,"is removed:",removecharacter(getstring,char_index))
Enter a string: Python is amaezing Enter the index position to remove: 13 Index no 13 is removed: Python is amazing
If we need to remove a specific character using value, then we can follow the below technique.
def removecharacter(name,value): for i in name: if value == i: name = name.replace(i,'') return name mystring = 'a;n;i;m;a;l' print("String:",mystring) print("Final string:",removecharacter(mystring, ';'))
String: a;n;i;m;a;l Final string: animal