Editor settings

General settings

Save settings

Learn to program with Python

Remove space from both ends of a string #

You can use the strip() method to remove whitespace from the beginning and end of a string.

For example, if you have a string s = " hello world ", you can use strip() to remove the whitespace like this:

s = "   hello world   "
s_stripped = s.strip()
print(s_stripped) # Output: "hello world"

The strip() method removes any whitespace characters (spaces, tabs, newlines) from the beginning and end of the string. If you want to remove whitespace only from the beginning or end of the string, you can use the lstrip() or rstrip() methods, respectively.


Exercise #

  • Use strip() method to remove all leading and trailing spaces before assigning the value to new_sentence
  • Keep the first line of code the same
Output will be displayed here