OneBite.Dev - Coding blog in a bite size

remove a character from a string in python

Code snippet on how to remove a character from a string in python

string = "Hello World!"
char = "l"

newString = string.replace(char,'')

print("Modified string:", newString)

The code above removes a character from a string in Python. Specifically, this code removes the letter ‘l’ from the string “Hello World!“. To begin, a string is declared with the value “Hello World!” and a char is declared with the letter ‘l’. The next line uses a string method called replace() to remove the letter ‘l’ from the string. This method takes two arguments, the character (in this case ‘l’) and what it should be replaced with, in this case nothing. The result of this method is assigned to the newString variable. Finally, the modified string is printed to the console.

python