How to remove a character from a string in Python 3?

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.

Code:

def removefirstcharacter(value):
    finalstring = value[1:]
    return finalstring
mystring = 'imy python string'
print("String:",mystring)
print("Final string:",removefirstcharacter(mystring))

Output:

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.

Code:

def removelastcharacter(value):
    finalstring = value[:-1]
    return finalstring
mystring = 'my python stringg'
print("String:",mystring)
print("Final string:",removelastcharacter(mystring))

Output:

String: my python stringg
Final string: my python string

Remove any specific character

Using pop():

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.

Code:

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))

Output:

Enter a string: Python is amaezing
Enter the index position to remove: 13
Index no 13 is removed: Python is amazing

Using value:

If we need to remove a specific character using value, then we can follow the below technique.

Code:

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, ';'))

Output:

String: a;n;i;m;a;l
Final string: animal