在Python正则表达式中拆分,带符号和大写字母

在Python正则表达式中拆分,带符号和大写字母,python,re,Python,Re,本着这个问题的精神:我想用格式将经度转换为十进制,例如,18-23-34W,即-18.392778。我想用负号,-和大写字母分开 我一直在尝试的链接中的功能适合我的需要: def dms2dd(s): degrees, minutes, seconds, direction = re.split('[A-Z-]+', s) dd = float(degrees) + float(minutes) / 60 + float(seconds) / (60 * 60) if d

本着这个问题的精神:我想用格式将经度转换为十进制,例如,18-23-34W,即-18.392778。我想用负号,-和大写字母分开

我一直在尝试的链接中的功能适合我的需要:

def dms2dd(s):
    degrees, minutes, seconds, direction = re.split('[A-Z-]+', s)
    dd = float(degrees) + float(minutes) / 60 + float(seconds) / (60 * 60)
    if direction in ('S', 'W'):
        dd *= -1
    return dd
问题似乎在于正则表达式的度数、分、秒、方向=re.split'[A-Z-]+',s。我得到的是转换,但不是应该得到的-1的乘法。Thx.

你的秒数会给你“34”-因为你删除了W:拆分字符永远不会保留

潜在修复:

import re

def dms2dd(s):
    degrees, minutes, seconds, *_ = re.split('[A-Z-]+', s)
    direction = s[-1]

    dd = float(degrees) + float(minutes)/60 + float(seconds)/(60*60)
    if direction in ('S','W'):
        dd*= -1
    return dd


print(dms2dd("18-23-34W"))  # -18.392777777777777  - add a round(_,6) to get yours
你的秒数会给你“34”-因为你删除了W:拆分字符永远不会保留

潜在修复:

import re

def dms2dd(s):
    degrees, minutes, seconds, *_ = re.split('[A-Z-]+', s)
    direction = s[-1]

    dd = float(degrees) + float(minutes)/60 + float(seconds)/(60*60)
    if direction in ('S','W'):
        dd*= -1
    return dd


print(dms2dd("18-23-34W"))  # -18.392777777777777  - add a round(_,6) to get yours