Check if a string ends with a decimal in Python 2
<p>I want to check if a string ends with a decimal of varying numbers, from searching for a while, the closest solution I found was to input values into a tuple and using that as the condition for endswith(). But is there any shorter way instead of inputting every possible combination?</p>

<p>I tried hard coding the end condition but if there are new elements in the list it wont work for those, I also tried using regex it returns other elements together with the decimal elements as well. Any help would be appreciated</p>

<pre><code>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'
</code></pre>

<p>Edit: Sorry should have specified that I do not want to have 'qwe -70' to be accepted, only those elements with a decimal point should be accepted</p>

<p>I'd like to propose another solution: using <a href="https://docs.python.org/2/library/re.html" rel="nofollow">regular expressions</a> to search for an ending decimal.</p>

<p>You can define a regular expression for an ending decimal with the following regex <code>[-+]?[0-9]*\.[0-9]+$</code>.</p>

<p>The regex broken apart:</p>

<ul>
<li><code>[-+]?</code>: optional - or + symbol at the beginning</li>
<li><code>[0-9]*</code>: zero or more digits</li>
<li><code>\.</code>: required dot</li>
<li><code>[0-9]+</code>: one or more digits</li>
<li><code>$</code>: must be at the end of the line</li>
</ul>

<p>Then we can test the regular expression to see if it matches any of the members in the list:</p>

<pre><code>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"
</code></pre>

<p>The output for the previous script is the following:</p>

<pre><code>abcd 1.01 passes
zyx 22.98 passes
efgh 3.0 passes
qwe -70 does not pass
test does not pass
</code></pre>

python list ends-with