Python 如何更改字符串中的特定字符?
我正在创建一个discord机器人,当我说的时候它会给我gif!特定频道中的gif。我面临的问题是,当我键入时,它无法将自身更改为%23,因为它在链接中使用。我只想用一种方法将字符串中的#更改为%23。请帮帮我。下面给出了整个代码。我对python非常陌生,因此如果您想要任何其他错误,请修复它并清理代码。我正在使用tenor API,谢谢 代码:Python 如何更改字符串中的特定字符?,python,discord.py,Python,Discord.py,我正在创建一个discord机器人,当我说的时候它会给我gif!特定频道中的gif。我面临的问题是,当我键入时,它无法将自身更改为%23,因为它在链接中使用。我只想用一种方法将字符串中的#更改为%23。请帮帮我。下面给出了整个代码。我对python非常陌生,因此如果您想要任何其他错误,请修复它并清理代码。我正在使用tenor API,谢谢 代码: import discord import os import json import requests import random client
import discord
import os
import json
import requests
import random
client = discord.Client()
global search_term_public
global url
search_term_public = "Rick Roll"
def tenor():
global url
# set the apikey
apikey = (os.getenv("TENORAPIKEY"))
# our test search
search_term = search_term_public
# get the GIFs for the search term
r = requests.get("https://g.tenor.com/v1/search?q=%s&key=%s&contentfilter=high" % (search_term, apikey))
if r.status_code == 200:
# load the GIFs using the urls for the smaller GIF sizes
top_8gifs = json.loads(r.content)
g = len(top_8gifs['results'])
i = random.randint(0,g)
if(i == g):
i = g-1
h = str(g)
f = str(i)
url = top_8gifs['results'][i]['media'][0]['gif']['url']
print("The number picked is " + f +" out of " + h + ". Search Term : " + search_term + ". Url : " +url)
else:
top_8gifs = None
return url
@client.event
async def on_ready():
print("Bot has successfully logged in as {0.user}".format(client))
@client.event
async def on_message(message):
global search_term_public
if message.author == client:
return
if message.content.startswith("!gif") and message.channel.id == 831789159587774504:
# put the search term into the public variable. split the content with space and the second or more than second word should be in a variable
tokens = message.content.split(' ')
if tokens.__contains__(""):
tokens.remove("!gif")
tokens.remove("")
elif tokens.__contains__("#"):
# I want to change # in the token and change it to %23
print()
else :
tokens.remove("!gif")
search_term_public = ("".join(tokens))
if search_term_public == "":
search_term_public = "Rick Roll"
await message.channel.send("You got rick rolled!")
url = tenor()
await message.channel.send(url)
client.run(os.getenv("DISCORDTOKEN"))
你想看看吗
可能吧
但是,要以热修复程序的形式直接回答这个问题,我认为您可以在.split()
行之后直接这样做
tokens = [token.replace('#', '%23') for token in tokens]
试试这个,可能有用 您可以按如下方式使用“替换”
elif tokens.__contains__("#"):
token=token.replace("#","%23")
要替换字符串中的字符,请使用
s.replace('#','%23')
。但是,tokens
不是一个字符串,它是一个字符串列表。你能解释一下代码和你的意思吗?我不明白,因为我对python很陌生。你看到的是一个字符串。如果我们尝试将此代码翻译成英语,听起来可能像:创建一个名为tokens
的新列表。然后,对于现有令牌列表中的每个令牌,对其应用函数,并将其保存到新的令牌
列表中,而不是原始值。当你需要获得一个新的列表,而这个列表是对现有列表中的每个成员进行一些小更改的结果时,列表理解是非常好的。我测试了它,你的答案也是正确的,但是堆栈溢出不允许我同时接受这两个答案,但请记住你的答案也是正确的