-3
string3 = "abc 123 $$%%"

list1 = string3.split()
print(list1)
for i in list1:
    if int(i) > 0:
        print("it's a number")
    else:
        print("not a number")

Getting below error :

if int(i) > 0:
ValueError: invalid literal for int() with base 10: 'abc'
mshsayem
  • 17,557
  • 11
  • 61
  • 69
  • 1
    What do you think `int('$$%%')` should return? – mshsayem Oct 12 '17 at 13:05
  • Possible duplicate of [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – Reti43 Oct 12 '17 at 13:06

5 Answers5

0
>>> str = "abc 123 $$%%"
>>> [int(s) for s in str.split() if s.isdigit()]
[123]
harshil9968
  • 3,254
  • 1
  • 16
  • 26
0

use i.isdigit()

string3 = "abc 123 $$%%"

list1 = string3.split() 
print(list1)
for i in list1:
    if i.isdigit():
        print("it's a number") 
    else: 
        print("not a number")
Complex
  • 341
  • 3
  • 9
0

Fancy way:

>>> s = "abc 123 $$%%"
>>> map(int,filter(str.isdigit,s.split()))
[123]

Explanation:

  • s.split() is splitting the string on spaces and generates: ['abc', '123', '$$%%']
  • str.isdigit is a function which returns True if all characters in the argument are digits.
  • filter filters out elements of a list which do not pass the test. First argument is the test function: str.isdigit, second argument is the list.
  • Finally, map transforms one list to another. First argument is the transform function int, second argument is the list found from filter.
mshsayem
  • 17,557
  • 11
  • 61
  • 69
0

try this

string3 = "abc 123 $$%%"

list1 = string3.split()
print(list1)
for i in list1:
    if i.isdigit():
        print("it's a number")
    else:
        print("not a number")

Output:
['abc', '123', '$$%%']
not a number
it's a number
not a number

0
string3 = "abc 123 $$%%"

list1 = string3.split()
print(list1)
for i in list1:
    try:
        int(i)
        print("It is a number")
    except ValueError:
        print("It is not a number")

Try this code