Python Remove Leading and Trailing Spaces from String
To remove leading and trailing spaces from a string, Python can use thestrip()method.
Here is an example of how to use it:
Example
stripped_string = original_string.strip()
print(stripped_string)
Executing the above code will remove the leading and trailing spaces from the string. The output result is as follows:
This is a string with spaces
However, if the string contains\nand other characters, and you only want to remove spaces, you need to explicitly specify it on the strip() method, as shown in the following code:
Example
print(my_string.strip(" "))
PythonWe can also use regular expressions to remove leading and trailing spaces from a string:
Example
my_string = " Hello Python "
output = re.sub(r'^\s+|\s+$', '', my_string)
print(output)
Executing the above code will output the following result:
Hello python
The strip() method will remove all whitespace at the beginning and end of the string (including spaces, tabs, and newlines).
In addition, Python provides two methods for removing leading and trailing spaces from a string:
- lstrip()-- Remove spaces at the beginning of the string.
- rstrip()-- Remove spaces at the end of the string.
Example
left_stripped_string = original_string.lstrip() # Remove leading spaces
right_stripped_string = original_string.rstrip() # Remove trailing spaces
print(left_stripped_string)
print(right_stripped_string)
Executing the above code will output the following result:
This is a string with spaces
This is a string with spaces
Other Extensions