How to remove a character from a string in python ?

Published: September 29, 2021

Updated: December 09, 2022

Tags: Python; Strings;

DMCA.com Protection Status

Examples of how to remove a character from a string in python:

Remove the n’th character from a string

Let's consider the following sentence:

sentence = "Hello, how are you ?"

To remove the n’th character (for example 4), a solution is to convert the string into a list:

sentence_list = list(sentence)

remove the element corresponding to index = 4:

sentence_list.pop(4)

and convert back to a string

sentence = "".join(sentence_list)

print(sentence)

gives

Hell, how are you ?

Replace a character by another character

Using Replace

If the goal is to replace a character by another character, a solution is to use replace():

sentence = "Hello, how are you ?"

sentence = sentence.replace("?", "!")

print(sentence)

gives

Hello, how are you !

Using Translate

Another solution is to use Python String translate() Method:

sentence = "Hello, how are you ?"

mytable = sentence.maketrans("?", "!")

sentence = sentence.translate(mytable)

print(sentence)

gives

Hello, how are you !

sentence = "Hello, how are you ?"

mytable = sentence.maketrans("hyo", "123")

sentence = sentence.translate(mytable)

print(sentence)

gives

Hell3, 13w are 23u ?

Remove leading spaces

Note: if the goal is to remove leading spaces, a solution is to use str.lstrip():

s = '           Hello World !'

s_new = s.lstrip()

    print(s_new)

returns then

Hello World !