【问题标题】:Looking for help to turn a large string into many smaller variables寻求帮助将大字符串变成许多较小的变量
【发布时间】:2021-08-30 22:28:09
【问题描述】:

我正在编写的一些代码有问题,我目前正在得到这个输出:{'footer': {'text': 'Item Type: Sellable'}, 'thumbnail': {'width': 75, 'url': 'https://cdn.discordapp.com/emojis/714980893999104051.png', 'proxy_url': 'https://images-ext-1.discordapp.net/external/c4teYBjoGAhxnygEZ5F2GlHWzReCIg_xEOX1PPtZdIQ/https/cdn.discordapp.com/emojis/714980893999104051.png', 'height': 75}, 'color': 15684432, 'type': 'rich', 'description': "This item's purpose is to be collected or sold. Nothing more, nothing less.\n\n**BUY** - Not able to be purchased\n**SELL** - ⏣ 1,680 (multiplier included)\n**TRADE** - 2k - 7k", 'title': '**Common Fish** (516 owned)'},我只想拥有最后一部分:(516 拥有)。我的目标是能够让 516 成为一个单独的变量,我可以在代码的其他部分中使用它。有人可以帮帮我吗?

【问题讨论】:

  • 你是把它作为一个字符串,还是把它作为一个对象?显然,作为一个对象,您只需要 obj['title'] 进行一点字符串处理即可。
  • 是字符串,有没有简单的转换方法?
  • 是的,如果是字符串,就是JSON。您可以使用json.loads() 方法将其转换为对象。

标签: python string discord


【解决方案1】:

考虑到你分享的输出已经是一个python字典,你可以调用title键,然后使用正则表达式提取你想要的数字。

import re

results = {
    'footer': {'text': 'Item Type: Sellable'}, 
    'thumbnail': 
    {
        'width': 75, 
        'url': 'https://cdn.discordapp.com/emojis/714980893999104051.png', 
        'proxy_url': 'https://images-ext-1.discordapp.net/external/c4teYBjoGAhxnygEZ5F2GlHWzReCIg_xEOX1PPtZdIQ/https/cdn.discordapp.com/emojis/714980893999104051.png', 
        'height': 75
    }, 
    'color': 15684432, 
    'type': 'rich', 
    'description': "This item's purpose is to be collected or sold. Nothing more, nothing less.\n\n**BUY** - Not able to be purchased\n**SELL** - ⏣ 1,680 (multiplier included)\n**TRADE** - 2k - 7k", 
    'title': '**Common Fish** (516 owned)'
}

var = int(re.search("\d+", results["title"])[0])
var
>>> 516

【讨论】:

  • 太棒了,感谢您的帮助,因为我对编码很陌生!我确实注意到您指定了宽度,如果我希望我的代码适用于任意长度的字符串,这仍然有效吗?
  • 这出现了一个错误,NameError: name 'd' is not defined
  • 他应该输入results而不是d,你应该能够弄清楚。
  • 更新了答案。我在最后一刻将变量名更新为results
猜你喜欢
  • 1970-01-01
  • 2020-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多