Most Pythonic way to extract a number from a string

Viewed 80

I have a string containing a number, starting with x, for example, "x270" or "x9". It always starts with x. I need to get the number.

I'm doing this:

blatz = "x22"
a1 = int(re.search("x(\d+)", blatz).group(1))

This doesn't seem very Pythonic. I would welcome more elegant solutions.

2 Answers

Using re library seems to be an overkill. You don't have to search for a pattern, because you're saying that each string starts with x.

So you simply can do slicing:

blatz = "x22"
a1 = int(blatz[1:])

If you need further checks, you can look at str.startswith(), str.endswith and/or str.isdigit().

While slicing looks very pythonistic, there is also the possibility to use other string methods that lead to the same goal:

blatz = "x22"
a2 = int(blatz.lstrip("x"))  # strip "x" from the left
a3 = int(blatz.partition("x")[-1])  # get everything after "x"
a4 = int(blatz.replace("x", ""))  # replace every "x" with empty string
...

But slicing is faster and nothing unusual for Python programmers.

Please check out this.

import re

blatz = "x22"
print(re.search("\d", blatz).group())

Related