You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在discord.py中将args的分隔符从空格改为逗号并正确分割参数

Fixing Comma-Based Argument Splitting in discord.py

Got it, let's get your comma-separated argument parsing sorted out for your discord.py bot! The core issue here is that discord.py splits command arguments by spaces by default, which is why you're getting messy results like ["1,", "3,", "5"] instead of clean separated values. Here's how to fix it properly:

The easiest way is to use *, args_str in your command function to capture everything after the command name as a single string. Then you can split this string by commas and clean up any extra whitespace:

@bot.command()
async def your_command(ctx, *, args_str):
    # Split the string by commas, then strip whitespace from each item
    # The `if item.strip()` filters out empty strings from extra commas
    parsed_args = [item.strip() for item in args_str.split(',') if item.strip()]
    
    # Now parsed_args will be ["1", "3", "5"] for input "1, 3, 5"
    await ctx.send(f"Parsed arguments: {parsed_args}")

This approach avoids the default space-splitting entirely, so you don't have to deal with commas stuck to your values.

Method 2: Fix Existing *args Input

If you prefer to stick with the *args syntax (which splits by spaces first), you can merge the args back into a single string and then process it:

@bot.command()
async def your_command(ctx, *args):
    # Merge the space-split args back into one string
    full_args = ' '.join(args)
    # Same cleaning step as Method 1
    parsed_args = [item.strip() for item in full_args.split(',') if item.strip()]
    
    await ctx.send(f"Parsed arguments: {parsed_args}")

Fixing Your Original Code

Your previous attempt had a syntax error with str.split()—the function doesn't accept a list of separators or a maxsplit as the first argument. For example, if you wanted to split into th and pp values (assuming you're pairing arguments like 1,2,3,4 into th=[1,3] and pp=[2,4]), here's how to do it after parsing:

@bot.command()
async def your_command(ctx, *, args_str):
    parsed_args = [item.strip() for item in args_str.split(',') if item.strip()]
    
    # Split into two lists: take every 2nd item starting at index 0 and 1
    th = parsed_args[::2]
    pp = parsed_args[1::2]
    
    await ctx.send(f"th values: {th}, pp values: {pp}")

If you just need the first two arguments as th and pp, you can do this instead:

if len(parsed_args) >= 2:
    th = parsed_args[0]
    pp = parsed_args[1]
    rest = parsed_args[2:]
    await ctx.send(f"th: {th}, pp: {pp}, extra: {rest}")
else:
    await ctx.send("Please provide at least two comma-separated arguments!")

内容的提问来源于stack exchange,提问作者BotBoi345

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 06:51:46