我如何检查列表中的值是整数还是字符串,并且如果它的整数是True
list = ["1 asd","sw asdd34","2asdas"]
如何检查该值是否以整数开头并返回True
或False
。
我尝试过:
for i in range(1, len(array)):
print("".join(array[i][:2]))
try:
if (int("".join(array[i][:4])) % 2 != 0):
top_row.insert(i,array[i])
print("port {} have been added on
top_row".format(array[i]))
elif (int("".join(array[i][:4])) % 2 == 0):
down_row.insert(i,array[i])
print("port {} have been added on
down_row".format(array[i]))
elif (int("".join(array[i][:4])) is not
(isinstance("".join(array[i][:4]), int))):
top_row.insert(i,"NONE")
print("add a none ")
else:
down_row.append(None)
答案 0 :(得分:2)
一个相当不错的Python语言而且实际上非常快的方法就是尝试。
a = someintorstring
try:
int(a)
# it's an int
except ValueError:
# not an int
pass
答案 1 :(得分:0)
它需要以整数开头吗?尝试正则表达式:
import re
for elem in your_list:
if re.match(r'^[0-9]+', elem):
# element starts with an integer, do your thing