Python - Check if the last characters in a string are numbers

Basically I want to know how I would do this.

Here's an example string:

string = "hello123"

I would like to know how I would check if the string ends in a number, then print the number the string ends in.

I know for this certain string you could use regex to determine if it ends with a number then use string[:] to select "123". BUT if I am looping through a file with strings like this:

hello123
hello12324
hello12435436346

...Then I will be unable to select the number using string[:] due to differentiation in the number lengths. I hope I explained what I need clearly enough for you guys to help. Thanks!

Answers


import re
m = re.search(r'\d+$', string)
# if the string ends in digits m will be a Match object, or None otherwise.
if m is not None:
    print m.group()

This doesn't account for anything in the middle of the string, but it basically says that if the last number is a digit, it ends with a number.

In [4]: s = "hello123"

In [5]: s[-1].isdigit()
Out[5]: True

With a few strings:

In [7]: for s in ['hello12324', 'hello', 'hello1345252525', 'goodbye']:
   ...:     print s, s[-1].isdigit()
   ...:     
hello12324 True
hello False
hello1345252525 True
goodbye False

I fully and completely support the regex solution(s), but here is one (not pretty) way you could get the number. Again, regex is much better here :)

In [43]: from itertools import takewhile

In [44]: s = '12hello123558'

In [45]: r = s[-1::-1]

In [46]: d = [c.isdigit() for c in r]

In [47]: ''.join((i[0] for i in takewhile(lambda (x, y): y, zip(r, d))))[-1::-1]
Out[47]: '123558'

This one will simply return an empty string if the string ends with something that is not a number.

import re
re.split('[^\d]', str)[-1]

Since an empty string is falsy, you can overload the meaning:

def getNumericTail(str):
    re.split('[^\d]', str)[-1]

def endsWithNumber(str):
    bool(getNumericTail(str))

another solution:

a = "abc1323"
b = ""
for c in a[::-1]:
    try:
        b += str(int(c))
    except: 
        break

print b[::-1]

Need Your Help

Android dialog across Activities

android android-activity popup

i'm new to Android, i'm looking to find if there a Dialog feature which stays at the bottom of the application, but across different activities.(Non modal dialog) It should not loose data if the

Trace / monitor a variable at runtime?

c# memory reflection garbage-collection runtime

I'm looking for a way to trace/monitor a variable at runtime (not for debugging) and throw certain events if it e.g. changes or falls out of the scope. Is there a .NET built-in way to do this? Like...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.