您如何检查字符串是否可转换为 int,如果是,则转换它? (Python,涉及discord.py重写)

How do you check if a string is convertible to an int, and if so, convert it? (Python, involves discord.py rewrite)

我目前正在 Python 制作一个不和谐的机器人。我想创建一个命令,其中您有两个参数选项:

我试过这样的函数来确定它是否是一个字符串...

def isint(s):
try:
    int(s)
    isint = True
except ValueError:
    isint = False
return isint

...但是 returns 这个错误:

TypeError: '<=' not supported between instances of 'str' and 'int'

这是我尝试过的命令的当前最新代码:

    @commands.command()
@commands.has_role("Clear Chat Key")
async def clear(self, ctx, amount: typing.Union[str, int] = 10):
    number = isint(amount)
    if number == False:
        if amount == 'all':
            await ctx.channel.purge(limit = inf)
        else:
            await ctx.send('Invalid amount.')
    if number == True:
        await ctx.channel.purge(limit = amount)
    else:
        await ctx.send('Invalid amount.')

如果相关,则错误的完整回溯如下:

Traceback (most recent call last):
  File "C:\Users794\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\bot.py", line 892, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users794\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 797, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users794\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 92, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: '<=' not supported between instances of 'str' and 'int'

请耐心等待,我是 Python 的新手。

编辑: 感谢您帮助我解决这个问题!这是我在其他人需要时使用的代码:

def is_int(x):
if x.isdigit():
    return True
return False

@commands.command()
@commands.has_role("Clear Chat Key")
async def clear(self, ctx, amount: typing.Union[str, int] = 10):
    number = is_int(amount)
    if number == False:
        if amount == 'all':
            await ctx.channel.purge(limit = inf)
        else:
            await ctx.send('Invalid amount.')
    if number == True:
        amount = int(amount)
        await ctx.channel.purge(limit = amount)
    else:
        await ctx.send('Invalid amount.')

再次感谢您的帮助!

试试用这个代替你的函数 isint:

# clear function
number = amount.__class__.__name__ == 'int'

您可以使用字符串的 .isdigit() 方法。

请记住,这将 return False 用于否定:

>>> my_str = "123"
>>> my_str.isdigit()
True
>>> other_str = "-123"
>>> my_str.isdigit()
False

工作示例:

def is_int(some_value):
    if some_input.isdigit():
        return True
    return False

some_input = input("Enter some numbers or words!\n-> ")
print(is_int(some_input))

参考: