OneBite.Dev - Coding blog in a bite size

trim a string in python

Code snippet on how to trim a string in python

  string_example = "    Hello World    "  
  # Trim the whitespace 
  trimmed_string_example = string_example.strip() 

This code will remove the leading and trailing whitespace of the string “Hello World”. It starts by creating a string called string_example and assigned the value ” Hello World ” which contains four white spaces at the beginning and four spaces at the end.

The second line of code trims the whitespace from the beginning and end of the string_example. To do this we use the string object’s strip method. This returns the string with the white space from the beginning and end removed and assigns this value to the trimmed_string_example.

python