問題描述
一段代碼阻礙了我在學校的 Discord 機器人 (One piece of code hindering my Discord bot for School)
我需要下面這行代碼來檢查用戶發送的整個數字的消息,而不是特定的數字(這是 5 的佔位符)
def check(m):
return m.content == '5' and m.channel == channel
幫助讚賞:)
參考解法
方法 1:
If you're expecting whole numbers, use str.isdecimal()
:
Return
True
if all characters in the string are decimal characters and there is at least one character,False
otherwise. Decimal characters are those that can be used to form numbers in base 10,
</blockquote>So your code would become:
def check(m): return m.content.isdecimal() and m.channel == channel
str.isdecimal()
works like:>>> '5'.isdecimal() True >>> '123'.isdecimal() True >>> '0'.isdecimal() # zero is okay True >>> '‑123'.isdecimal() # doesn't work for negative integers False >>> '3.76'.isdecimal() # doesn't work for floats False >>> ''.isdecimal() # doesn't work for empty strings False
方法 2:
If you want to check whether a string contains a number, use the isdigit() method (returns a boolean).
string = '1234' print (string.isdigit())
(by Keigen Sheppard、aneroid、TheChicken4452)
參考文件