You cannot use a regular expression in the replace()
method for strings, you have to use the re module:
import re
mystring = re.sub(r'\s+', ' ', mystring)
Note the r
prefix before the string literal, this makes sure that the backslash in your regular expressions is interpreted properly. It wouldn't actually make a difference here, but for different escape sequences it can cause serious problems. For example '\b'
is a backspace character but r'\b'
is a backslash followed by a 'b', which is used for matching word boundaries in regex.