开发者

Check what number a string ends with in Python

S开发者_运维技巧uch as "example123" would be 123, "ex123ample" would be None, and "123example" would be None.


You can use regular expressions from the re module:

import re
def get_trailing_number(s):
    m = re.search(r'\d+$', s)
    return int(m.group()) if m else None

The r'\d+$' string specifies the expression to be matched and consists of these special symbols:

  • \d: a digit (0-9)
  • +: one or more of the previous item (i.e. \d)
  • $: the end of the input string

In other words, it tries to find one or more digits at the end of a string. The search() function returns a Match object containing various information about the match or None if it couldn't match what was requested. The group() method, for example, returns the whole substring that matched the regular expression (in this case, some digits).

The ternary if at the last line returns either the matched digits converted to a number or None, depending on whether the Match object is None or not.

 


I'd use a regular expression, something like /(\d+)$/. This will match and capture one or more digits, anchored at the end of the string.

Read about regular expressions in Python.


Oops, correcting (sorry, I missed the point)

you should do something like this ;)

Import the RE module

import re

Then write a regular expression, "searching" for an expression.

s = re.search("[a-zA-Z+](\d{3})$", "string123")

This will return "123" if match or NoneType if not.

s.group(0)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜