1

我想检查一个字符串是否以不同数字的小数结尾,通过搜索一段时间,我找到的最接近的解决方案是将值输入一个元组并将其用作endswith()的条件。但是有没有更短的方法来代替输入所有可能的组合?

我尝试对结束条件进行硬编码,但如果列表中有新元素,它将不适用于这些元素,我还尝试使用正则表达式,它也会返回其他元素以及小数元素。任何帮助,将不胜感激

list1 = ["abcd 1.01", "zyx 22.98", "efgh 3.0", "qwe -70"]

for e in list1:
    if e.endswith('.0') or e.endswith('.98'):
        print 'pass'

编辑:抱歉应该指定我不想接受'qwe -70',只接受那些带小数点的元素

4

6 回答 6

2

我想提出另一种解决方案:使用正则表达式搜索结尾小数。

您可以使用以下 regex 为结尾小数定义正则表达式[-+]?[0-9]*\.[0-9]+$

正则表达式分解:

  • [-+]?: 可选 - 或 + 符号开头
  • [0-9]*: 零个或多个数字
  • \.: 必填点
  • [0-9]+: 一位或多位数字
  • $: 必须在行尾

然后我们可以测试正则表达式,看看它是否匹配列表中的任何成员:

import re

regex = re.compile('[-+]?[0-9]*\.[0-9]+$')
list1 = ["abcd 1.01", "zyx 22.98", "efgh 3.0", "qwe -70", "test"]

for e in list1:
  if regex.search(e) is not None:
    print e + " passes"
  else:
    print e  + " does not pass"

上一个脚本的输出如下:

abcd 1.01 passes
zyx 22.98 passes
efgh 3.0 passes
qwe -70 does not pass
test does not pass
于 2016-09-24T06:02:18.323 回答
0

您的示例数据留下了许多可能性:

最后一个字符是一个数字:

e[-1].isdigit()

最后一个空格之后的所有内容都是一个数字:

try:
    float(e.rsplit(None, 1)[-1])
except ValueError:
    # no number
    pass
else:
    print "number"

使用正则表达式:

re.match('[.0-9]$', e)
于 2016-09-24T05:46:54.960 回答
0
suspects = [x.split() for x in list1] # split by the space in between and get the second item as in your strings

# iterate over to try and cast it to float -- if not it will raise ValueError exception

for x in suspects:
    try:
        float(x[1])
        print "{} - ends with float".format(str(" ".join(x)))
    except ValueError:
        print "{} - does not ends with float".format(str(" ".join(x)))

## -- End pasted text --

abcd 1.01 - ends with float
zyx 22.98 - ends with float
efgh 3.0 - ends with float
qwe -70 - ends with float
于 2016-09-24T05:47:54.313 回答
0

我认为这适用于这种情况:

regex = r"([0-9]+\.[0-9]+)"

list1 = ["abcd 1.01", "zyx 22.98", "efgh 3.0", "qwe -70"]

for e in list1:
    str = e.split(' ')[1]
    if re.search(regex, str):
       print True #Code for yes condition
    else:
       print False #Code for no condition
于 2016-09-24T05:58:04.693 回答
0

正如您正确猜测endswith()的那样,考虑到组合的数量基本上是无限的,这不是查看解决方案的好方法。正如许多人所建议的那样,要走的路是一个正则表达式,它将字符串的结尾匹配为小数点,后跟任意位数。除此之外,保持代码简单易读。在strip()那里,以防万一输入字符串末尾有一个额外的空格,这会使正则表达式不必要地复杂化。您可以在以下网址看到这一点:https ://eval.in/649155

import re
regex = r"[0-9]+\.[0-9]+$"

list1 = ["abcd 1.01", "zyx 22.98", "efgh 3.0", "qwe -70"]

for e in list1:
    if re.search(regex, e.strip()):
       print e, 'pass'
于 2016-09-24T06:09:58.787 回答
0

流动可能有帮助:

import re

reg = re.compile(r'^[a-z]+ \-?[0-9]+\.[0-9]+$')

if re.match(reg, the_string):
    do something...
else:
    do other...
于 2016-09-24T06:11:02.713 回答