If I have a string 'x=10'
, how can I extract the 10 as an integer using one line of code?
views:
236answers:
5Thanks very much
mikip
2010-01-04 15:38:38
+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
2010-01-04 15:38:34
To account for the possibility of something like `x=y=500`, I would use `rpartition` instead of `partition`.
jcdyer
2010-01-04 15:52:35
**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
2010-01-04 16:31:11
@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
2010-01-04 17:12:23