Remove unwanted spaces between quotations

Viewed 1096

Is there a more elegant way to remove spaces between quotations (despite using code like this:

input = input.replace('" 12 "', '"12"')`)

from a sentence like this:

 At " 12 " hours " 35 " minutes my friend called me.

Thing is that numbers can change, and then the code won't work correctly. :)

3 Answers

You can use regular expressions as long as your quotations are reasonably sane:

re.sub(r'"\s*([^"]*?)\s*"', r'"\1"', input)

The pattern reads as "quote, any number of spaces, stuff that's not a quote (captured), followed by any number of spaces and a quote. The replacement is just the thing you captured in quotes.

Notice that the quantifier in the capture group is reluctant. That ensures that you don't capture the trailing spaces.

You can try using a regular expression, such as the one below:

"\s+(.*?)\s+"

This matches any substring of any length containing any character which is not a newline, surrounded by whitespace and quotation marks. By passing this to re.compile(), you can use the returned Pattern object to call the sub() method.

>>> import re
>>> string = 'At " 12 " hours " 35 " minutes my friend called me.'
>>> regex = re.compile(r'"\s+(.*?)\s+"')
>>> regex.sub(r'"\1"', string)
'At "12" hours "35" minutes my friend called me.'

The \1 calls for the first group to be substituted, in this case the string matched by .*?

Here's a solution I came up with real quick that will work for any numbers you input.

input = 'At " 12 " hours " 35 " minutes my friend called me.'

input = input.split()

for count, word in enumerate(input):
    if input[count] == '"':
        del input[count]
    if input[count].isdigit():
        input[count] = '"' + input[count] + '"'

str1 = ' '.join(input)
print('Output:')
print(str1)

Output:

>>> Output:
>>> At "12" hours "35" minutes my friend called me.
Related