pythonstringeval

How to use eval() function on string of ints?


With a string of ints:

myStr = '3848202160702781329 2256714569201620911 1074847147244043342'

How could one do an average of the string ints while keeping the string data type? Here what I thought in pseudo code:

sum = 0
res = eval(myStr[i] + ' + sum') 
avg = res/len(myStr)

Solution

  • If You want to get the average of those integers in that string this is one way:

    myStr = '3848202160702781329 2256714569201620911 1074847147244043342'
    print(sum(lst := [int(x) for x in myStr.split()]) / len(lst))
    

    basically You get the sum of a list of those integers that are in that string and also use that operator (forgot the name) to assign that list to a variable while simultaneously return that value, then just divide the sum by the length of that list

    EDIT1, 2, 3: just remembered, it is called walrus operator, some info can be found here (video by Lex Fridman) and here, as well as other places, also it requires Python version of 3.8 or higher

    EDITn: the reason behind the use of the walrus operator is that it allowed to not repeat code in this one-liner, otherwise the list comprehension would have been used twice (in sum and in len) which could affect performance for very large lists (and I wanted it to be a one-liner)