Finding double spaces in a string - Python

Can someone find a more Python'ic, more beautiful solution?

Im looping through some text lines in a file to check if they meet certain criteria. For some reason, it was decided that the delimiters inside the line have a value '', i.e. Double space.

How to check a text string to make sure that all delimiters are exactly two spaces? Spaces at the end of a line are not a problem, since the line is originally .strip () ed.

I wrote this and it works - but its ugly. The code will be shown to some Python newbies, so Im looking for a shorter, clearer and more beautiful solution ...

ll = ["53.80  64-66-04.630N  52-16-15.355W 25-JUN-1993:16:48:34.00  S10293..  2",
      " 53.80  64-66-04.630N  52-16-15.355W  25-JUN-1993:16:48:34.00  S10293..  2",
      "53.80  64-66-04.630N  52-16-15.355W  25-JUN-1993:16:48:34.00  S10293..  2",
      "  53.80  64-66-04.630N  52-16-15.355W  25-JUN-1993:16:48:34.00  S10293..  2",
      "53.80  64-66-04.630N  52-16-15.355W  25-JUN-1993:16:48:34.00  S10293..  2 ",
      "53.80  64-66-04.630N  52-16-15.355W  25-JUN-1993:16:48:34.00  S10293..  2  ",
      "53.80  64-66-04.630N  52-16-15.355W   25-JUN-1993:16:48:34.00  S10293..  2"]

for ln in ll:
    l = ln.strip()
    bolDS = True
    for n in range(len(l)-1):
        if (n>0 and l[n]==' ' and not ((l[n]==l[n+1])^(l[n]==l[n-1]))):
            bolDS = False

    print "|"+l+"|",bolDS
+5
source share
3 answers
def is_doublespace_separated(input_string):
    return '  '.join(input_string.split()) == input_string.strip()

, string.split . string.join string. ' ' ( ) , ( , , ).

** , .

+10

:

import re

s = "53.80  64-66-04.630N  52-16-15.355W 25-JUN-1993:16:48:34.00  S10293..  2"
s2 = "53.80  64-66-04.630N  52-16-15.355W  25-JUN-1993:16:48:34.00  S10293..  2"

def spaceTest(line):
    matches = re.findall(r'\s+', line.strip())
    return not any(m for m in matches if m != '  ')

print spaceTest(s)
# False
print spaceTest(s2)
# True

:

s.strip().count('  ')+1 == len(s.split())

, 1 , .

+4

, , ( split/join @mgilson , ):

import re

ok = re.match(r'(?:\S|(?<!\s)  (?!\s))*$', line)

: , .

0

All Articles