1

I'm making a function that evaluates maths in a string. First, it takes the string and then converts it to a list.

I tried converting the entire array into an array of integers, but I run into an error when the array looks like this: ["hello",1,"*",2] as everything isn't a number.

I want to only convert the integers in the array ["1","2","hello","3"] to integers, so the array becomes [1,2,"hello",3]

That way, I can do maths on the integers and not have them treated as strings, as currently, when I do this:

1 + 2

I get 12 as the output. I want 3 as the output.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Auxilor
  • 49
  • 1
  • 8
  • Loop over the list and [check if each string value represents an int](https://stackoverflow.com/questions/1265665/how-can-i-check-if-a-string-represents-an-int-without-using-try-except) before converting. Something like `new_list = [int(x) if is_int(x) else x for x in my_list]` where can use the `is_int()` function from the post I linked. – pault May 20 '19 at 14:57
  • You haven't shown any code, and what is supposed to happen with `"hello"`? – roganjosh May 20 '19 at 14:57
  • Possible duplicate of [How can I check if a string has a numeric value in it in Python?](https://stackoverflow.com/questions/12466061/how-can-i-check-if-a-string-has-a-numeric-value-in-it-in-python) – pault May 20 '19 at 15:00

1 Answers1

1

You can use a list comprehension with str.isdigit() and int():

ls = ["1", "2", "hello", "3"]
new_ls = [int(n) if n.isdigit() else n for n in ls]
print(new_ls)

Output:

[1, 2, 'hello', 3]

 

You can also add str.lstrip() to make it work with negative numbers:

ls = ["1", "-2", "hello", "-3"]
new_ls = [int(n) if n.lstrip('-').isdigit() else n for n in ls]
print(new_ls)

Output:

[1, -2, 'hello', -3]
ruohola
  • 21,987
  • 6
  • 62
  • 97