python – Remove all whitespace in a string
python – Remove all whitespace in a string
If you want to remove leading and ending spaces, use str.strip()
:
sentence = hello apple
sentence.strip()
>>> hello apple
If you want to remove all space characters, use str.replace()
:
(NB this only removes the “normal” ASCII space character U+0020
but not any other whitespace)
sentence = hello apple
sentence.replace( , )
>>> helloapple
If you want to remove duplicated spaces, use str.split()
:
sentence = hello apple
.join(sentence.split())
>>> hello apple
To remove only spaces use str.replace
:
sentence = sentence.replace( , )
To remove all whitespace characters (space, tab, newline, and so on) you can use split
then join
:
sentence = .join(sentence.split())
or a regular expression:
import re
pattern = re.compile(rs+)
sentence = re.sub(pattern, , sentence)
If you want to only remove whitespace from the beginning and end you can use strip
:
sentence = sentence.strip()
You can also use lstrip
to remove whitespace only from the beginning of the string, and rstrip
to remove whitespace from the end of the string.
python – Remove all whitespace in a string
An alternative is to use regular expressions and match these strange white-space characters too. Here are some examples:
Remove ALL spaces in a string, even between words:
import re
sentence = re.sub(rs+, , sentence, flags=re.UNICODE)
Remove spaces in the BEGINNING of a string:
import re
sentence = re.sub(r^s+, , sentence, flags=re.UNICODE)
Remove spaces in the END of a string:
import re
sentence = re.sub(rs+$, , sentence, flags=re.UNICODE)
Remove spaces both in the BEGINNING and in the END of a string:
import re
sentence = re.sub(^s+|s+$, , sentence, flags=re.UNICODE)
Remove ONLY DUPLICATE spaces:
import re
sentence = .join(re.split(s+, sentence, flags=re.UNICODE))
(All examples work in both Python 2 and Python 3)