views:

236

answers:

5

If I have a string 'x=10', how can I extract the 10 as an integer using one line of code?

+1  A: 
answer = int("x=10".partition("=")[2])
Pace
+7  A: 
>>> s = "x=10"
>>> int(s.split('=')[-1])
10
Antoine P.
+3  A: 
s = 'x=10' 
i = int(s[2:])
apt
+4  A: 

Sure:

a = "x=10"
b = int(a.split('=')[1])
Adam Crossland
Thanks very much
mikip
+2  A: 
result = int(my_string.rpartition("=")[-1])

Note, however, that if there is anything else after the = sign the function will break.

So x=10, x=560, and x=1010001003010 will all work. However, y=1,341 will break with a ValueError.

ValueError: invalid literal for int() with base 10: '1,341'

Edit: Actually, pitrou's use of split is even better, since you probably are not guaranteed that there will be only one = sign either.

And also fixed the partition vs. rpartition problem.

Sean Vieira
To account for the possibility of something like `x=y=500`, I would use `rpartition` instead of `partition`.
jcdyer
**OP doesn't have such problem**. With you attitude we'll get to parsing random binary blobs because these *numbers* are not guaranteed to be at end of string, not guaranteed to be digits, not guaranteed to be ascii strings.
SilentGhost
@SilentGhost -- absolutely true. I wasn't trying to suggest that his code **should** be robust enough to handle `1,341`, only pointing out that it wouldn't. A note of caution, rather than a suggestion that a more "robust" solution was needed.
Sean Vieira