2016-09-24 84 views
1

我想检查一个字符串是否以不同数字的小数结尾,从搜索一段时间后,我发现最接近的解决方案是将值输入到一个元组中,作为endswith()的条件。但是有没有更简单的方法,而不是输入每种可能的组合?检查一个字符串是否以Python中的小数结尾2

我试图编码最终条件,但如果列表中有新元素,它不会为那些工作,我也尝试使用正则表达式它返回其他元素与小数元素一起以及。任何帮助,将不胜感激

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”被接受,只能用小数点这些元素应该被接受

+0

有啥小数的定义是什么?为什么不是1.01小数。 – Daniel

+1

它看起来每个字符串中的数字都被一个空格分隔,所以为什么不只是'float(e.split()[ - 1])',并且在引发'ValueError'时返回false? – ozgur

回答

2

我想提出另一种解决方案:使用regular expressions搜索为结尾小数。

您可以使用以下正则表达式[-+]?[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 
+0

完美地工作,只接受带小数点的元素。谢谢 – SSY

0

你的榜样数据留下了许多可能性敞开:

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

e[-1].isdigit() 

一切是一个数字:

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

使用正则表达式:

re.match('[.0-9]$', e) 
+0

这将接受我不想要的'qwe -70',只有​​其他3个应该被接受 – SSY

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 
+0

这会返回'qwe -70',但我只想让列表中有小数点的那些元素像其他3 – SSY

+0

如果你想检查一个数字是否是整数,你可以使用is_integer方法浮点数。检查小数点可能需要regex或再次分割并检查。 https://docs.python.org/2/library/stdtypes.html#float.is_integer –

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 
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' 
0

的可能流动的帮助: 您可以在行动看到这个

import re 

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

if re.match(reg, the_string): 
    do something... 
else: 
    do other... 
相关问题