How to Remove all Whitespace in a String in Python
Created
Modified
Using str.replace Function
The str.replace(x)
function returns a copy of the string with all occurrences of substring old replaced by new.
See the following example:
#!/usr/bin/python3
s = " \nHello World "
n = s.replace(" ", "")
print('{!r}'.format(n))
'\nHelloWorld'
Using str.split Method
If you want to remove spaces, use str.split() followed by str.join():
#!/usr/bin/python3
s = " \nHello World "
n = ''.join(s.split())
print('{!r}'.format(n))
'HelloWorld'
Using regular Expression
To remove all whitespace characters (space, tab, newline, and so on) you can use a regular expression:
#!/usr/bin/python3
# Import module
import re
s = " \nHello World "
n = re.sub(r"\s+", "", s, flags=re.UNICODE)
print('{!r}'.format(n))
'HelloWorld'