0
eval("".join(token.lstrip('0') for token in s.split()))

Where s is something like '02 + 00030 - 76'.

All I know is that it strips the zeroes in front of the 02 and 00030 so that it can evaluate it as 2+30-76. However, I don't understand how exactly it does this. Could someone explain this combination of functions to me?
Thanks so much.

user3666197
  • 1
  • 6
  • 50
  • 92
M. Freberg
  • 39
  • 1
  • 7

3 Answers3

2

Lets break it down by starting with the expressions inside.

token.lstrip('0') for token in s.split()

In Python, this is a generator expression. Rather than evaluating the statement and creating a list from the expression and storing in memory, the generator expression will create each element, one at a time so you can actually use it for very large (and even infinite!) sequences without sacrificing performance.

s.split() returns a list by splitting a string by its whitespace. Therefore, this line means, "for each token in the string, strip out all the 0's at the beginning of the string.

"".join(//result of inner expression)

This is a performant way in Python of creating a string by using a list. This basically concatenates each element in the list with an empty string.

eval

This evaluates the argument as a Python expression.

Josh Hamet
  • 957
  • 8
  • 10
2
for token in s.split()

s.split() evaluates to ['02', '+', '00030', '-', '76']

Then you do token.strip('0') which converts the list to - ['2', '+', '30', '-', '76'] by removing leading 0s from each token.

Finally "".join([..]) joins them back into '2+30-76'.

eval evaluates this expression to get an integer.

PS: It is a very bad idea to use eval on unsanitized user input text. Imagine what will happen if the user enters some malicious code as input.

Ajay Brahmakshatriya
  • 8,993
  • 3
  • 26
  • 49
0

s.split() creates a list of strings formed by the whitespace-separated parts of s.

(... for token in s.split()) iterates through each of the strings in that list.

token.lstrip('0') removes leading zeros from each string.

"".join glues together all the zero-removed tokens, so "".join(token.lstrip('0') for token in s.split()) is now a string that looks like an arithmetic expression.

eval("".join(token.lstrip('0') for token in s.split())) tells Python to treat the string as Python code, so it returns an int rather than a str. BTW, using eval is generally a bad idea.

The final result is the original string, with whitespace removed, evaluated as a number.

perigon
  • 2,160
  • 11
  • 16