42

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!

4

5 に答える 5

63
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()

\d matches a numerical digit, \d+ means match one-or-more digits (greedy: match as many consecutive as possible). And $ means match the end of the string.

于 2013-01-23T01:53:57.490 に答える
35

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'
于 2013-01-23T01:50:48.887 に答える
2

文字列が数値ではない何かで終わる場合、これは単に空の文字列を返します。

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

空の文字列はfalsyであるため、意味をオーバーロードできます。

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

def endsWithNumber(str):
    bool(getNumericTail(str))
于 2013-01-23T02:04:53.347 に答える
0

別の解決策:

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

print b[::-1]
于 2013-01-23T01:59:52.313 に答える