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'
>>> str = "abc 123 $$%%"
>>> [int(s) for s in str.split() if s.isdigit()]
[123]
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")
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.map
transforms one list to another. First argument is the transform function int
, second argument is the list found from filter
.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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.