如何在s.isdigit()命令中识别-1000这样的数字?

时间:2018-09-11 05:30:37

标签: python-3.x

我的问题很简单:

如何使python3能够识别s.isdigit()上的-1000或某种命令?我的程序必须能够将-1000分隔为数字分类...我一直在绞尽脑汁以发现该怎么做...我应该使用什么命令将它识别为减号(-)号码?

line_number=int(input())
counter=0
counter_2=0
counter_hashtag=0
counter_3=0
counter_emoticons=0
list_strings=[]
i=0


while(counter<line_number):
    a=str(input())
    counter=counter+1
    list_strings.append(a)

for i in range(0,len(list_strings)):
    try:
        int(list_strings[i])
        is_int = True
        print("Hello")
    except ValueError:
        is_int = False
    if(list_strings[i].isalpha() or is_int):
        print(list_strings[i])
    else:
        if((list_strings[i])[0]=='#'):
            if((list_strings[i])[1:].isalpha()):
                counter_hashtag=counter_hashtag+1
             else:
                counter_emoticons=counter_emoticons+1
        else:
            if(not (list_strings[i])[0]=="-"):
                counter_emoticons=counter_emoticons+1
    counter_3=counter_3+1
    ############################################################################
    ############################################################################
    if(counter_hashtag>1):
        print(counter_hashtag, "hashtags were removed.")
    if(counter_hashtag==1):
        print("1 hashtag was removed.")
    if(counter_emoticons>1):
        print(counter_emoticons, "emoticons were removed.")
    if(counter_emoticons==1):
        print("1 emoticon was removed.")

1 个答案:

答案 0 :(得分:0)

您只需在try-except构造函数周围使用int块来测试字符串是否包含有效整数:

try:
    int(list_strings[i])
    is_int = True
except ValueError:
    is_int = False

因此,您的for循环应作如下修改:

for i in range(0,len(list_strings)):
    try:
        int(list_strings[i])
        is_int = True
        print("Hello")
    except ValueError:
        is_int = False
    if(list_strings[i].isalpha() or is_int:
        print(list_strings[i])
    else:
        if((list_strings[i])[0]=='#'):
            if((list_strings[i])[1:].isalpha()):
                counter_hashtag=counter_hashtag+1
            else:
                counter_emoticons=counter_emoticons+1
        else:
            if(not (list_strings[i])[0]=="-"):
                counter_emoticons=counter_emoticons+1
    counter_3=counter_3+1