OneBite.Dev - Coding blog in a bite size

remove a substring from a string in python

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

  s = 'Hello World' 
  substring = 'World' 
  
  # use the replace() method 
  s = s.replace(substring, '') 
  
  print(s) 

This code removes a substring from a string. It starts by creating two strings “s” and “substring”. “s” is the initial string, which is “Hello World”, and “substring” is the string that is going to be removed from “s”, which is “World”.

Next, it uses the replace() method, which takes two parameters, “substring” and an empty string ”, to remove the substring from the string. Finally, it prints the new modified string. In this example, the output would be “Hello”.

python