【问题标题】:How do I properly use the strip() type?如何正确使用 strip() 类型?
【发布时间】:2021-09-25 17:07:24
【问题描述】:

我目前正在尝试制作一个不和谐的机器人。我正在尝试对其进行设置,以便它将在控制台中发送一条消息,即(用户)在(通道)中发送了(命令)命令。 ctx 的工作方式,字符串总是有一个前导和尾随空格。我想知道如何删除所述空格。如您所见,我尝试使用 .strip,但它根本不起作用。

def receivedcommand(ctx):
    print(current_datetime,'INFO: Chat Command Received;',ctx.author.name,'sent \"',ctx.message.content.strip(),'\" in \"#',ctx.channel.name.strip()[2:],'\"')

[2:] 用于删除我服务器中的前缀,在本例中是表情符号和不和谐兼容的管道。

那个函数返回

[07/16/21 21:03:39] INFO: Chat Command Received; Vyladence sent " |parrot awa2 " in "# programming "

在收到 Vyladence 在#programming 中发送的|parrot 命令时。有人知道我在这里搞砸了什么吗?

【问题讨论】:

  • strip 是一种方法,而不是一种类型。
  • 对不起,我是 python 新手。周二才开始学习。

标签: python python-3.x discord discord.py


【解决方案1】:

您实际上已将其剥离,因为您使用的是逗号,所以它会自动添加一个空格分隔符,要修复它,请尝试以下操作:

print(current_datetime,'INFO: Chat Command Received;',ctx.author.name,'sent \"',ctx.message.content.strip(),'\" in \"#',ctx.channel.name.strip()[2:],'\"', sep='')

例子:

使用逗号打印会自动添加空格分隔符,如下所示:

>>> print('a', 'b')
a b
>>> 

添加sep=''(将分隔符分配给空字符串)就可以了:

>>> print('a', 'b', sep='')
ab
>>> 

【讨论】:

    【解决方案2】:

    您确实剥离了任何要剥离的空间。 print 本身就是在"ctx.message.content.strip() 的值之间添加空格。

    不要将多个参数传递给print,而是考虑构建一个字符串:

    print(f'{current_datetime} INFO: Chat Command Received; ctx.author.name sent "{ctx.message.content.strip()}" in "#{ctx.channel.name.strip()[2:]}"')
    

    【讨论】:

      猜你喜欢
      • 2022-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-25
      相关资源
      最近更新 更多