【问题标题】:Strip characters from a list从列表中删除字符
【发布时间】:2022-01-08 13:25:20
【问题描述】:

我有一个在 python 脚本上运行的不和谐机器人,它的令牌存储在 .txt 文件中。如果我从文件中读取:

with open('Stored Discord Token.txt') as storedToken:
    TOKEN = storedToken.readlines()

我可以获得不和谐机器人令牌。问题是不和谐机器人令牌看起来像这样:

[' <token> ']

这会在尝试运行脚本时导致错误,并且机器人无法连接,因为它是无效的令牌:

discord.errors.LoginFailure: Improper token has been passed.

如何从包含令牌的列表中删除方括号、's 和空格?


TL;DR:如何从单个项目列表中删除 []'spaces

【问题讨论】:

  • 如果您绝对确定令牌字符串具有这种形式,为什么不切出适当的子字符串?
  • @Brian 原来我对我的问题的回答是简单地做string[-1] 删除不需要的字符......我偶然发现......

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


【解决方案1】:

首先,read() 只会将整个文件内容作为字符串返回,因此您可以使用TOKEN = storedToken.read()

可以使用[index] 访问Python 中的列表,因此要访问文件中的第一行,您可以使用TOKEN = storedToken.readlines()[0]。如果说你想访问nth 行,你可以做storedToken.readlines()[n]。其中nint

【讨论】:

  • 原来我把它弄得更复杂了,它应该是......谢谢!
【解决方案2】:

正如@Brian 所建议的,切出子字符串可以解决问题。如果我们简单地添加一行代码,像这样:

with open('Stored Discord Token.txt') as file:
    fileContents = file.readlines()
    TOKEN = fileContents[-1]

我们删除了[]' 字符,现在可以成功地将该字符串作为令牌传递。

【讨论】:

    【解决方案3】:

    试试这个:

    import re
    a=[' <token123> ']
    re.sub(r'[^a-zA-Z0-9]', '', str(a))
    

    【讨论】:

      猜你喜欢
      • 2015-10-25
      • 1970-01-01
      • 2015-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-24
      相关资源
      最近更新 更多