How to remove a character from a string in Python?

In Python, you can use the replace() and translate() methods to remove characters you want to remove from a string and return a new modified string result.

Strings, and especially user-generated input may contain unwanted characters, such as special characters in a username field we don’t want to store. In those cases, we might prefer to remove specific characters from a given string.

In this article, I will show you how to work with the replace() and translate() methods to remove characters from a string in Python.

Remove Character from a string in Python using replace()

The string class provides a replace() method, that replaces a character with another. It’s worth noting that his function returns a new string with the characters replaced, since strings are immutable. The original string remains unchanged, but the object in memory is lost unless we keep a reference to it alive. Typically, you’ll assign the returned value either to the same pointer or a new one.

The method replaces all occurrences of a character, with a new one. For example, any_string.replace('a', 'b') will replace all occurrences of 'a' in any_string with the character 'b'. To remove a character from a string via replace(), we’ll replace it with an empty character:

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

print("Your username is: " + final_username)

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.

If you want to remove the central character:

midlen = len(oldstr) // 2
newstr = oldstr[:midlen] + oldstr[midlen+1:]

Output:

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.

Quick note:

To replace a specific position:

s = s[:pos] + s[(pos+1):]

To replace a specific character:

s = s.replace('M','')

How to remove multiple characters using replace() in python?

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 characters from a string in python using translate()

Python strings have a translate() method which replaces the characters with other characters specified in a translation table.

translation table is just a dictionary of key-value mappings where each key will be replaced with a value.

For this method to work, we have to specify the Unicode value for the strings, which we can get via the ord() function.

For example, any_string.ranslate({ord('a'):ord('z'), ord('b'):ord('y')}) will replace occurrences of 'a' with 'z' and 'b' with 'y'.

To remove a character from a string using translate(), you’ll need to map the Unicode value of the character with None in the translation table.

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.

How to remove multiple characters from a string 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.

How to remove last character from a string in Python?

Method 1: Slicing

Python supports negative index slicing along with positive slicing. Negative index starts from -1 to -(iterable_length). We will use the negative slicing to get the elements from the end of an iterable.

  • The index -1 gets you the last element from the iterable.
  • The index -2 gets you the 2nd last element from the iterable.
  • And it continuos till the first element.

Let’s see an example.

name = 'Geekflare'
print(name[-1])
print(name[-len(name)])

The above program will print the last and first characters from the string using negative indexing.

How do we remove the last element from the string using slicing? It’s just a line of code. We know how to extract a part of the string using slicing. Let’s apply the same thing with a negative index to remove the last character from the string.

  • Slice the string from start to the last before element.
buggy_name = 'GeekflareE'
name = buggy_name[:-1]
print(name)

Let’s focus on the second line in the above code. That’s the magic line in the code. As a traditional slicing, it extracts the substring from the starting index to last but one as slicing ignores the second index element given.

You will get Geekflare as output if you run the above code.

Method 2: rstrip

The string method rstrip removes the characters from the right side of the string that is given to it. So, we can use it to remove the last element of the string. We don’t have to write more than a line of code to remove the last char from the string.

  • Give the last element to the strip method, it will return the string by removing the last character.

Let’s see the code snippet.

buggy_name = 'GeekflareE'
name = buggy_name.rstrip(buggy_name[-1])
print(name)

We have given the last character of the string to the strip method. It removes the last character from the string and returns a copy without the last character.

It will print Geekflare in the console, if you execute it.

Practical Example – remove the last word from a string in Python

Yeah, we are going to apply what we have in the previous sections in a practical example.

Let’s say we have a file that contains multiple lines of text. And we need to remove the last word from each line in the file.

Follow the below steps to write the program.

  • Create a file called random_text.txt and page a few lines of text in it.
  • Initialize a data variable as an empty string.
  • Open the file using with and open method in read and write mode.
  • Read the content of the file using the readlines method.
  • Iterate over each line of the content.
    • Split the line of text using the split method in words.
    • Remove the last word using one of the above methods.
    • Join the result to form a string.
    • Append the result to the data variable.
  • Remove the data from the file using seek and truncate methods.
  • Write the latest data to the file using write method.

The file contains the following data.

This is a sample line for testing. LastWord.
This is a sample line for testing. KillingIt.
This is a sample line for testing. RandomWord.
This is a sample line for testing. DeleteIt.
This is a sample line for testing. RemovingIt.

See the code below.

updated_data = ''

# opening the file
with open('random_text.txt', 'r+') as file:
    # read the file content
    file_content = file.readlines()

    # iterate over the content
    for line in file_content:

        # removing last word
        updated_line = ' '.join(line.split(' ')[:-1])

        # appending data to the variable
        updated_data += f'{updated_line}\n'

    # removing the old data
    file.seek(0)
    file.truncate()

    # writing the new data
    file.write(updated_data)

If you execute the above code with the given file, then the file will have the following updated data.

This is a sample line for testing.
This is a sample line for testing.
This is a sample line for testing.
This is a sample line for testing.
This is a sample line for testing.

Remove a Number of Occurrences of a Character from a string in Python

The replace() and translate() methods replace all the occurrences of a given character with another. However, the replace() method takes an optional argument count. If it is given, it only replaces count the number of occurrences of the given character.

Let’s try only removing the first 'a' from the string, instead of all occurrences:

original_string = "Programming articles"
# removing character 'a'
new_string = original_string.replace('a',  '', 1)
print("String after removing the character 'a':", new_string)

The output of the above code will look like this:

String after removing the character 'a': Progrmming articles

As the count is set to 1, only the first occurrence of 'a' is replaced – this is useful when you want to remove one and only one character.

Conclusion

In this article, we explored how we can remove characters from a string in Python. We have seen how to use the replace() and translate() methods to remove characters by replacing them with an empty string or their Unicode with None.

Later, we have used replace() to remove a predefined number of occurrences of the given character, and even the good old for loop. The translate() method is useful if we have to remove a set of characters, as we can give it a translation table. And the replace() method is handy if we want to remove a number of occurrences of a given character.

It is important to remember that the original string will not be altered because strings are immutable.

Here is the basic syntax for the replace() method.

str.replace(old_str, new_str[, optional_max])

The return value for the replace() method will be a copy of the original string with the old substring replaced with the new substring.

Another way to remove characters from a string is to use the translate() method. This method returns a new string where each character from the old string is mapped to a character from the translation table and translated into a new string.

Here is the basic syntax for Python’s translate() method.

str.translate(table)

About ᴾᴿᴼᵍʳᵃᵐᵐᵉʳ

Linux and Python enthusiast, in love with open source since 2014, Writer at programming-articles.com, India.

View all posts by ᴾᴿᴼᵍʳᵃᵐᵐᵉʳ →