If I have a string 'x=10', how can I extract the 10 as an integer using one line of code?
-
I'll give you a hint: split, int, len, assertHamish Grubijan– Hamish Grubijan2010-01-04 15:32:46 +00:00Commented Jan 4, 2010 at 15:32
-
2"One line" isn't important, but I understand you to mean simple, clear code.Roger Pate– Roger Pate2010-01-04 15:41:06 +00:00Commented Jan 4, 2010 at 15:41
-
1No not homework, just trying to learn pythonmikip– mikip2010-01-05 09:01:45 +00:00Commented Jan 5, 2010 at 9:01
-
Four different solutions, each upvoted, meaning they provide some value to visitors and thus the question also provides value, yet the question is downvoted. That's not the way to go.duality_– duality_2013-03-27 15:21:04 +00:00Commented Mar 27, 2013 at 15:21
Add a comment
|
5 Answers
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.
3 Comments
jcdyer
To account for the possibility of something like
x=y=500, I would use rpartition instead of partition.SilentGhost
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.
Sean Vieira
@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.