Home > Net >  Strip characters from a list
Strip characters from a list

Time:12-02

I have a discord bot running on a python script, and its token is stored in a .txt file. If I read from the file using:

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

I can get the discord bot token. The problem is that the discord bot token looks like this:

[' <token> ']

This causes an error when trying to run the script, and the bot fails to connect, as it is an invalid token:

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

How do I remove the square brackets, 's and spaces from the list containing the token?


TL;DR: How to remove [, ], ', and spaces from a single item list?

CodePudding user response:

First of all, read() will just return the whole file contents as a string, so you could use TOKEN = storedToken.read().

Lists in Python can be accessed using [index] so to access the first line in the file you can do TOKEN = storedToken.readlines()[0]. If say you wanted to access the nth line you could do storedToken.readlines()[n]. Where n is an int.

CodePudding user response:

As @Brian suggested, slicing out the substring solves the problem. If we simply add one line of code, like this:

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

we remove the [, ], ', and characters, and can now successfully pass that string as the token.

CodePudding user response:

Try this one:

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