Search code examples
pythonstringruntime-error

"TypeError: not all arguments converted during string formatting" when trying to find even numbers


I am getting this error on Python 3, TypeError: not all arguments converted during string formatting. I know this is due to the string starting with "[" but the problem I'm solving has this as the input string '[1, 2, 3, 4, 5, 6, 7, 8, 9]' and the task is to find the even numbers on Python 3. Any help would be much appreciated.

def is_even_num(l):
  enum = []
  for n in l:
     if n % 2 == 0:
       enum.append(n)
  return enum
print(is_even_num('[1, 2, 3, 4, 5, 6, 7, 8, 9]'))
TypeError: not all arguments converted during string formatting

If I try int(n), I get this error

ValueError: invalid literal for int() with base 10: '['

Edit 1:

A similar problem I am facing due to the input being a STRING

Python Exercise: Sort a tuple by its float element

price = "[('item1', '12.20'), ('item2', '15.10'), ('item3', '24.5')]" 
print( sorted(price, key=lambda x: float(x[1]), reverse=True)) 
IndexError: string index out of range 

Here 'Price' is a string and the problem is to Sort a tuple by its float element

  1. Program to transpose a matrix using a nested loop

    y = "[[1,2,3,4],[4,5,6,7]]"
    result = [[0,0],
      [0,0],
      [0,0],
      [0,0]]
    
    #iterate through rows
    for i in range(len(X)):
    # iterate through columns
        for j in range(len(X[0])):
            result[j][i] = X[i][j]
    for r in result:
        print(r)
    
IndexError: list index out of range

I am getting this same type of problem again, the matrix has been input as a STRING.


Solution

  • Remove [ and ] and split the string:

    def is_even_num(l):
      enum = []
      for n in l.replace('[','').replace(']','').split(', '):
        if int(n) % 2 == 0:
           enum.append(n)
      return enum
    print(is_even_num('[1, 2, 3, 4, 5, 6, 7, 8, 9]'))
    

    Output:

    ['2', '4', '6', '8']
    

    Another ellegant way is to use ast:

    def is_even_num(l):
      enum = []
      for n in ast.literal_eval(l):
        if int(n) % 2 == 0:
           enum.append(n)
      return enum
    print(is_even_num('[1, 2, 3, 4, 5, 6, 7, 8, 9]'))
    

    Output:

    ['2', '4', '6', '8']
    

    Also for you second part of your question as said before just use ast:

    price = "[('item1', '12.20'), ('item2', '15.10'), ('item3', '24.5')]"  
    price = ast.literal_eval(price) 
    print( sorted(price, key=lambda x: float(x[1]), reverse=True))
    

    Output:

    [('item3', '24.5'), ('item2', '15.10'), ('item1', '12.20')]
    

    Then:

    y = "[[1,2,3,4],[4,5,6,7]]"
    result = [[0,0],
     [0,0],
     [0,0],
     [0,0]]
    X = ast.literal_eval(y)
    #iterate through rows
    for i in range(len(X)):
    # iterate through columns
        for j in range(len(X[0])):
            result[j][i] = X[i][j]
    for r in result:
      print(r)
    

    Output:

    [1, 4]
    [2, 5]
    [3, 6]
    [4, 7]