Python 3.x 如何在s.isdigit()命令上识别像-1000这样的数字?
我的问题很简单: 例如,如何使python3在s.isdigit()或某种命令上识别-1000?我的程序必须能够分开-1000作为一个数字分类。。。我一直在绞尽脑汁想知道怎么做。。。我应该使用什么命令来识别减号(-)作为数字的一部分Python 3.x 如何在s.isdigit()命令上识别像-1000这样的数字?,python-3.x,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=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.")
line\u number=int(输入())
计数器=0
计数器2=0
计数器\u hashtag=0
计数器3=0
计数器图标=0
列表_字符串=[]
i=0
而(1):
打印(计数器_标签,“标签已删除”)
如果(计数器标签==1):
打印(“删除了1个标签”)
如果(计数器表情>1):
打印(计数器表情符号,“表情符号已删除”)
如果(计数器表情==1):
打印(“删除了1个表情符号”)
您只需在int
构造函数周围使用try except
块来测试字符串是否包含有效整数:
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
它不起作用。。。它仍然将-1000识别为表情符号:/程序没有识别try,除了block之外,我认为它肯定会工作。你能通过更新你的问题或编辑我的答案来显示你的更新代码吗?我看到了你的更新代码。我的答案中的
是布尔值,用来代替你的isdigit
测试。您不应使用isdigit
保留原始代码。将(list_strings[i]).isdigit()
替换为is_int
,并删除不必要的if(is_int==True):print(is_int)if(is_int==False):
语句,您的代码就可以工作了。我猜.py归档文件已损坏,因为我将所有内容复制到了另一个归档文件,并且它工作正常:)非常感谢