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>As you correctly guessed, <code>endswith()</code> is not a good way to look at the solution, given that the number of combinations is basically infinite. The way to go is - as many suggested - a regular expression that would match the end of the string to be a decimal point followed by any count of digits. Besides that, keep the code simple, and readable. The <code>strip()</code> is in there just in case one the input string has an extra space at the end, which would unnecessarily complicate the regex.
You can see this in action at: <a href="https://eval.in/649155" rel="nofollow">https://eval.in/649155</a></p>

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

python list ends-with