python - 如何删除变量中的 {''}?
问题描述
我最近做了一个命令,将信息保存到 JSON 文件中。所以基本上,我有 2 个命令,第一个命令设置全局变量,第二个命令使用提供的变量添加到 JSON 文件中。一旦我对其进行测试,它会将文本保存为全局变量,然后将其保存为 JSON 文件{'test'}
。我不想要{''},所以有没有办法没有{''},只有文字test
?
脚本:
#global variables
namereg = None
cbreg = None #more
bdreg = None
descreg = None
libreg = None
invreg = None
btreg = None
ssreg = None
slugreg = None
@client.command(pass_context=True)
async def namereg(ctx, *, arg):
global namereg
namereg = {arg}
embed = discord.Embed(title='Registed Name.',description=f'Set the name as {arg}',colour=discord.Color.dark_green())
print(f'{arg}')
await ctx.send(embed = embed)
@client.command(pass_context=True)
async def add(ctx):
role_names = [role.name for role in ctx.message.author.roles]
if "Server Moderator" in role_names:
def write_json(data, filename='bots.json'):
with open (filename, "w") as f:
json.dump(data, f, indent=4)
with open ('bots.json') as json_file:
data = json.load(json_file)
temp = data["bots"]
y = {"name": f"{namereg}"}
temp.append(y)
write_json(data)
embed = discord.Embed(title='Added!',description='Successfully added with the following!',timestamp=ctx.message.created_at,colour=discord.Color.dark_green())
await ctx.send(embed = embed)
如果有办法没有{''},请回复此线程!谢谢你。
解决方案
问题:
namereg = None
@client.command(pass_context=True)
async def namereg(ctx, *, arg):
global namereg
这已破了。代码顶层的函数是全局变量,并且在同一个命名空间中。给它一个与存储变量不同的名称。
namereg = {arg}
这将获取来自用户输入的字符串,并创建一个包含单个元素的集合。那不是你想要的。您希望输入字符串是注册名称,所以直接分配它。
y = {"name": f"{namereg}"}
我假设您进行了这种奇特的格式化,因为您之前遇到了错误(因为json
默认情况下不会序列化集合,因为 JSON 数据格式没有直接的方式来表示它们)。您应该更仔细地聆听此错误消息,首先询问您为什么拥有无效类型的数据。输出中的{}
and''
来自您使用字符串格式进行字符串化的集合的字符串表示形式。您要使用的纯字符串不需要任何格式即可转换为字符串,因为它已经是字符串。
推荐阅读
- influxdb - 启动influxDB时非法标签0
- python - 如何显示包含该行中特定值的确切列
- flutter - 将容器缩小到较小的孩子而不是扩大到填充父母
- android - 如何从 AdapterView父级中提取 Spinner Layout id?
- ios - ObsetveSingleEvent 错误处理
- python - 无法使用 Python 抓取具有不变 URL 的多个页面
- gradle - 多项目 gradle 无法正确导入
- php - 如果 phpmailer 中的字段为空,则不显示消息文本
- javascript - 添加输入时,我的 javascript 代码中断
- laravel - 无法将图像存储到公共存储(LARAVEL)