Technology

Python Remove Character from String: A Guide

You can remove a character from a Python string using replace() or translate(). Both these methods replace a character or string with a given value. If an empty string is specified, the character or string you select is removed from the string without a replacement.

Python Remove a Character from a String

Not every string contains the values we want them to contain. A user may insert a symbol into an input field that you do not want to appear. You may want to remove any instances of a particular letter from a string.

It doesn’t matter what character you want to remove from a string. Python has you covered!

In this guide, we’re going to discuss how to remove a character or set of characters from a string. We’ll refer to some examples along the way.

We’ll discuss the following approaches:

  • Using the replace() method
  • Using the transform() method
  • Removing the last character using indexing

Let’s begin!

Remove Character from String Python: replace()

The string replace() function replaces a character with a new character. This function can be used to replace any character with a blank string.

We’re building a program that asks a user to insert a username. Underscore (_) characters are not allowed in a username. Open up a new Python file and paste in the following code:

username = input("Choose a username: ")
final_username = username.replace("_", "")

print("Your username is: " + final_username)

This code asks the user to choose a username by using the input() method.

The replace() method removes the underscore character from the original string and replaces all instances of that character with an empty string. Then, we print out the username without underscores to the console.

Let’s run our program:

Choose a username: pythonista_101
Your username is: pythonista101

Our code has removed the underscore character from the username that we specified. Our code works on strings that do not contain an underscore:

Choose a username: pythonista101
Your username is: pythonista101

When a username does not include an underscore, nothing happens.

Remove Multiple Characters Using replace()

What happens if you want to remove multiple characters from a string? Python can help you out. We can use the replace() method inside a for loop to remove multiple characters from a string.

In our last example, we removed an underscore character from a username. What if we want to remove all periods (full stops), underscores, and exclamation marks from our string? Create a new Python file and paste in this code:

username = input("Choose a username: ")
disallowed_characters = "._!"

for character in disallowed_characters:
	username = username.replace(character, "")

print("Your username is: " + username)

First, we have asked a user to choose a username. We have then defined a string which contains all the characters that should not appear in a user’s username.

Next, we have created a for loop. This for loop iterates through every character in the “disallowed_characters” string. In each iteration, the character the for loop is iterating over will be replaced in the “username” string with a blank character.

Let’s run our code:

Choose a username: pythonista.101!!!
Your username is: pythonista101

Our code has filtered out the period and the exclamation marks.

Remove Character from String Python: translate()

The Python translate() method replaces characters in a string according to the contents of a character table. This method accepts one argument: the translation table with characters to map.

To use this method, we need to create a translation table. This table specifies what characters should be replaced in a string.

Let’s use the translate() method to remove all the underscores from a username:

username = input("Choose a username: ")
final_username = username.translate({ ord("_"): None })

print("Your username is: " + final_username)

This code replaces every instance of the “_” character with a None value. The Python ord() method returns the Unicode code associated with the “_” character. This is used by the translate() method to identify the character that we want to remove.

Remove Multiple Characters Using translate()

You can remove multiple characters from a string using translate().

We can do this by creating an iterator which loops through a list of characters that we want to remove from a string.

Let’s remove all underscores, periods, and exclamation marks from a username:

username = input("Choose a username: ")
final_username = username.translate({ ord(c): None for c in "._!" })

print("Your username is: " + final_username)

The translate() method checks whether each character in the “username” string is equal to either a full stop, an exclamation point, or an underscore. If one of these characters is found, it is replaced with None. This removes the character from the string.

We are using a Python list comprehension to iterate through every character in our excluded characters list.

Let’s test our program:

Choose a username: pythonista_100!
Your username is: pythonista101

Our code has successfully removed all the special characters we specified from our string.

Python: Remove Last Character from String

To remove the last character from a string, use the [:-1] slice notation. This notation selects the character at the index position -1 (the last character in a list). Then, the syntax returns every character except for that one.

The syntax for removing the last character from a string is:

your_string = "A string"

print(your_string[:-1])

Remove Last Character Example

We want to build a program that removes the last character from an employee identifier. This character tells us the department for which an employee works.

For instance, the value “M” tells us an employee works for the marketing department. We are going to remove this character. This system of tracking employees is being replaced by a new system. The new system keeps track of the department for which an employee works.

Let’s start by asking the user to insert an employee identifier using the input() method:

identifier = input("What is the employee's identifier? ")

Next, we remove the last character from the identifier:

new_identifier = identifier[:-1]

The [:-1] is a string slice operation that removes the last character from the list. We use negative indexing to retrieve items from the end of the string. Now, display an employee’s new identifier to the console:

print("The employee's new identifier is {}.".format(new_identifier))

The format() statement replaces the curly braces inside our string with the employee’s new identifier. Let’s run our code and see what happens:

What is the employee's identifier? 28371M
The employee's new identifier is 28371.

Our program removes the last value in an employee’s identifier.

Conclusion

You can remove a character or multiple characters from a string using replace() or translate(). Both the replace() and translate() methods return the same outcome: a string without the characters you have specified.

For beginners, the replace() method is easier to use. This is because it only accepts two parameters.

The first parameter is the character you want to replace. Our second parameter is the value with which you want to replace the character. If you want to replace multiple characters, you can use a for loop.

Are you interested in learning more about Python? Check out our complete How to Learn Python guide for expert tips to help you advance your learning journey.

Click to rate this post!
[Total: 0]
Subscribe Our Newsletter Don't worry. We wont spam you.

Author

The Articledesk Editorial team is responsible for this post. For collaborations and partnership requests, kindly send an email to the Editorial Team at contact[at]articledesk[dot]net for the terms and conditions. You can also follow Articledesk.net on Twitter here and like our page on Facebook here.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

Login for fast comment.

Login

close

About Us

We ensure that current articles are collected at one table for all writers and blog readers.

Follow Us