[英]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.这是我在 stackoverflow 中的第一篇文章,希望我能得到我的问题的答案。 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".
我正在尝试在 html 页面上打印从 python 代码发送的字符串,但是当我在 html 页面上返回字符串时,它向我显示此错误:“ValueError:索引 650 处不支持的格式字符 'w' (0x77)”。 This is the python code:
这是python代码:
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:虽然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> </p>
<p> </p>
<h1 style="text-align: center;"> Response</h1>
<p> </p>
<p> </p>
<!--The string specified in the python script after % will go instead of %s-->
<h3 style="text-align: center;">%s</h3>
<p> </p>
<p> </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":就个人而言,我宁愿使用“替换”:
%s
I would use something like ___RESPONSE_VALUE___
%s
我会使用类似___RESPONSE_VALUE___
out = resp.replace("___RESPONSE_VALUE___", "Registered")
out = resp.replace("___RESPONSE_VALUE___", "Registered")
For more complex items, I suggest you to check Jinja2 library, it is excellent for templating对于更复杂的项目,我建议你查看 Jinja2 库,它非常适合模板
The problem here is that you have a % w
in your html file.这里的问题是您的 html 文件中有一个
% w
。
The "%" operator in python search for all %
character in the string and do some replacement based on what's next. python 中的“%”运算符搜索字符串中的所有
%
字符,并根据接下来的内容进行一些替换。
To keep the "%s" as the placeholder value, replace all litteral %
by %%
.要将 "%s" 保留为占位符值,请将所有文字
%
替换为%%
。
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
.正如其他提到的,占位符最好使用“%s”以外的其他内容,例如
___RESPONSE_VALUE___
、 {{ RESPONSE_VALUE }}
或使用模板系统(例如jinja
)。
PS: Python also has the str.format
function that's more advanced than "%" : PS:Python 还有比 "%" 更高级的
str.format
函数:
print("Hello {} !".format("You"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.