If I have a string
"this is a string"
How can I shorten it so that I only have one space between the words rather than multiple? (The number of white spaces is random)
"this is a string"
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You could use
string.splitand" ".join(list)to make this happen in a reasonably pythonic way – there are probably more efficient algorithms but they won’t look as nice.Incidentally, this is a lot faster than using a regex, at least on the sample string:
Compiling this regex does improve performance, but only if you do call
subon the compiled regex, instead of passing the compiled form intore.subas an argument: