简体   繁体   中英

ValueError: unsupported format character 'w' (0x77) at index 650

This is my first post in stackoverflow and hopefully I get an answer for my question. I am trying to print on an html page a string sent from a python code, but when I return the string on the html page it shows me this error: "ValueError: unsupported format character 'w' (0x77) at index 650". This is the python code:

def doctor_post(self, name, userID, password, telegramID):
    resp=open("response.html").read()
    new = {
        "name": name,
        "userID": userID,
        "password": password,
        "telegramID": telegramID,
        "patientsList": []
    }
    r = requests.post(self.Catalog+"/doctor", json=new)
    if r.status_code==200:
        out=resp % "Registered"
        return out

While the html:

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title>Response</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>


<body>
    <p>&nbsp;</p>
    <p>&nbsp;</p>
    <h1 style="text-align: center;"> Response</h1>

    <p>&nbsp;</p>
    <p>&nbsp;</p>
    <!--The string specified in the python script after % will go instead of %s-->
    <h3 style="text-align: center;">%s</h3>
    <p>&nbsp;</p>
    <p>&nbsp;</p>
    <p style="text-align: center;"><input type="button" onclick="document.location.href='/';" value="Homepage"><br></p>

</body>
</html>

Personally for something like this I rather use "replace":

  • in the html, instead of %s I would use something like ___RESPONSE_VALUE___
  • in the python code out = resp.replace("___RESPONSE_VALUE___", "Registered")

For more complex items, I suggest you to check Jinja2 library, it is excellent for templating

The problem here is that you have a % w in your html file.

The "%" operator in python search for all % character in the string and do some replacement based on what's next.

To keep the "%s" as the placeholder value, replace all litteral % by %% .

As other mentioned, it's better to use something else than "%s" for the placeholder, like ___RESPONSE_VALUE___ , {{ RESPONSE_VALUE }} or using a templating system like jinja .

PS: Python also has the str.format function that's more advanced than "%" :

print("Hello {} !".format("You"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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