How to remove a character from a string in python ?

September 29, 2021    /    Viewed: 164    /    Comments: 0    /    Edit


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 !

References


Card image cap
profile-image
Daidalos

Hi, I am Ben.

I have developed this web site from scratch with Django to share with everyone my notes. If you have any ideas or suggestions to improve the site, let me know ! (you can contact me using the form in the welcome page). Thanks!