Remove all whitespace in a string
You can remove all whitespace in a string in Python by using the replace()
method and replacing all whitespace characters with an empty string. Here's an example code snippet:
original_string = " This is a string with lots of whitespace. "
modified_string = original_string.replace(" ", "")
print(modified_string)
This will output:
Thisisastringwithlotsofwhitespace.
Watch a video course
Python - The Practical Guide
You can also use the join()
function with a generator comprehension to remove all whitespaces
original_string = " This is a string with lots of whitespace. "
modified_string = ''.join(original_string.split())
print(modified_string)
This will also output:
Thisisastringwithlotsofwhitespace.
Both of the above code snippets will remove all whitespaces in the original string and assign the modified string to the variable modified_string
.