Can anyone find a more Python’ic, more beautiful solution?
I’m looping through some text lines in a file, to check if they meet certain criteria.
For some reason it was decided that separators internally in the line is ‘ ‘, i.e. double space.
How do I check a text string to verify that all separators are exactly two spaces?
Spaces at the end of the line is not an issue, as the line is initially .strip()’ed.
I have written this, and it works – but it’s ugly.
The code will be shown to some Python newbie’s, so I’m 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
This works because
string.splitwill split your string on any whitespace. andstring.joinjoins the list with the separatorstring. In this case, we use the separator' '(two spaces) to re-join your string and then compare it against the stripped version (I sense you already know what strip does).**This will ignore whitespace at the front of the string as well as at the end.