【问题标题】:How to verify string type geographic coordinates are in the correct format?如何验证字符串类型的地理坐标格式是否正确?
【发布时间】:2021-11-23 01:47:35
【问题描述】:

我有:

coordinates = '50.0572, 1.20575'

坐标是字符串类型。

50.0572 是纬度 1.2057 是经度

我想找到最简单的解决方案来验证坐标的格式是否为:XX.XX, XX.XX

示例:如果坐标 = '120, 1.20' => False => 格式错误(120 错误)

谢谢。

【问题讨论】:

  • 我想用正则表达式检查字符串

标签: python python-3.x regex


【解决方案1】:

你可以先.split(',')然后检查.isdigit()如果得到True你有int号码,你找到bad format

试试这个:

>>> coordinates = '120, 1.20'
>>> [cor.isdigit() for cor in coordinates.split(',')]
[True, False]

>>> coordinates = '50.0572, 1.20575'
>>> if not any(cor.isdigit() for cor in coordinates.split(',')):
...    print("we don't have bad format")

we don't have bad format

如果您想使用regex,您可以使用re.compile(),然后使用match,如下所示:

>>> import re
>>> flt_num = re.compile(r'\d+.\d+')

>>> coordinates = '120, 1.20'
>>> for cor in coordinates.split(','):
...    if flt_num.match(cor):
...        print(f'{cor} has bad format')

120 has bad format

【讨论】:

  • 我想用正则表达式检查格式
  • @meuhfunk 欢迎
猜你喜欢
  • 2014-03-25
  • 1970-01-01
  • 2018-11-28
  • 1970-01-01
  • 1970-01-01
  • 2013-01-03
  • 1970-01-01
  • 2019-03-18
  • 1970-01-01
相关资源
最近更新 更多