简体   繁体   English

如何更改字符串中的特定字符?

[英]How to change a particular char in a string?

I am creating a discord bot that gives me gif when I say.gif in a particular channel.我正在创建一个 discord 机器人,当我在特定频道中 say.gif 时,它会给我 gif。 The problem I am facing is when I type # it cannot change itself to %23 as it is used in links.我面临的问题是,当我键入 # 时,它无法将自身更改为 %23,因为它在链接中使用。 I just want a way to change # in the string to %23.我只是想要一种将字符串中的 # 更改为 %23 的方法。 Please help me for that.请帮助我。 The whole code is given below.整个代码如下。 I am very new to python so if you want any other errors please fix it and also clean up the code.I am using the tenor API Thank you我对 python 非常陌生,所以如果您想要任何其他错误,请修复它并清理代码。我使用的是男高音 API 谢谢

Code:代码:

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"))

You want to look at url encoding probably.您可能想查看url 编码

However, to directly answer the question as a hotfix, I think you can do this directly after the .split() line但是,要直接作为修补程序回答问题,我认为您可以在.split()行之后直接执行此操作

tokens = [token.replace('#', '%23') for token in tokens]

Try this, it might work试试这个,可能有用

You can just use the "replace" as follows您可以按如下方式使用“替换”

elif tokens.__contains__("#"):
        token=token.replace("#","%23")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM