Replacing multiple spaces in Python

  • Context: Python 
  • Thread starter Thread starter tabc
  • Start date Start date
  • Tags Tags
    Multiple Python
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
1 reply · 3K views
tabc
Messages
5
Reaction score
0

Homework Statement



Write a function spacereplace(txt) that removes two or more spaces in a row, replacing them with a single space. Any other characters should remain the same.

The Attempt at a Solution



I tried this:

def spacereplace(txt):
f=txt.replace(" "," ")
return f

This obviously just works when there are two spaces. I have no idea how to make it work for 2+.

This method apparently works:

def spacereplace(txt):
txt.split()
f=" ".join(txt.split())
return f

But it is not beeing accepted. Any ideas?
 
Physics news on Phys.org


Hello!

Here is one possible solution to your problem:

def spacereplace(txt):
new_txt = ""
prev_char = ""
for char in txt:
if char == " " and prev_char == " ":
continue
else:
new_txt += char
prev_char = char
return new_txt

Explanation: This function loops through each character in the input string and checks if it is a space. If it is, it also checks the previous character. If the previous character was also a space, it skips adding the current space to the new string. Otherwise, it adds the current character to the new string. This way, it only adds a single space even if there are multiple consecutive spaces.

I hope this helps! Let me know if you have any further questions or if this solution doesn't work for you. Good luck!