
Replace multiple spaces of a string with one space in Python
How can we replace multiple spaces of a string with one space in Python? Using the replace()
as follows is incorrect.
s = 'it is an apple .'
t = s.replace(' ', ' ')
print(t) # it is an apple .
Replacing two spaces with one space doesn't replace four spaces with one space so there are two spaces between it
and is
. The simplest way to convert multiple spaces to one space is splitting a string by a space and concatenating words with a space.
s = ' it is an apple . '
a = s.strip()
b = ' '.join(s.split())
print(a) # it is an apple .
print(b) # it is an apple .
Note that the strip()
removes leading and trailing spaces. The split()
splits a string by one space into a list of words.
s = ' it is an apple . '
x = s.split()
b = ' '.join(x)
print(x) # ['it', 'is', 'an', 'apple', '.']
print(b) # it is an apple .
The join()
is a string method that concatenates all the elements in a list. In this case, (one space) is a "glue" of it.
Comments
Powered by Markdown