trim() 在 Python 中使用 Flask 函数
trim() function in Python using Flask
python中是否有类似trim()的函数?
我使用 Flask miniframework 但它不接受:
selected_student = (request.args.get('student_form')).strip()
它的错误:AttributeError: 'NoneType' object has no attribute 'strip'
selected_student.replace(" ", "")
它的错误:AttributeError: 'NoneType' object has no attribute 'replace'
我需要像 trim() 这样的函数,而无需编写 class/subclass 或 javascript
有一个 strip() 方法。您得到的错误是因为您试图在 NoneType 对象上 运行 它。您需要 运行 它在字符串对象上。
>>> s = 'some string '
>>> s.strip()
'some string'
还有字符串替换:
>>> s.replace('some', 'many')
'many string '
您遇到的问题与其他问题有关。您以 None 对象结束,而不是您想要获得的对象。
您看到您看到的错误是因为没有数据 从您的表单传递到 Flask 服务器。您对 request
的使用返回的是 None
值类型,而不是 str
.
您张贴了以下 HTML 表单标记:
<form action="/student" method='POST'>
<select name="student_form ">
{% for student in students_list %}
<option value="{{student}}">{{student}}</option>
{% endfor %}
</select>
<input type='submit' value='submit' />
</form>
因此,您需要在某个地方让 Flask 在服务器端获取这些数据,例如:
@app.route('/student', methods=['POST'])
def receive_student_form_data:
my_selection = str(request.form.get('student_form')).strip()
print(my_selection)
只是为了阐明我以这种方式制作我的方法的原因:我注意到您正在使用 request.args.get()
来检索表单发送的值。这是不正确的。
request.args
用于从 URL.
中检索键/值对
request.form
用于从 HTML 表单中检索键/值对。
所以我建议您改用 request.form.get('student_form')
。如果你真的想确定它在你的 Flask 服务器检索时被转换为 str
,那么你可以将它转换为 str
,如下所示:
str(request.form.get('student_form'))
然后,正如一些人已经建议的那样,您可以使用 .strip()
方法删除任何尾随空格。
python中是否有类似trim()的函数?
我使用 Flask miniframework 但它不接受:
selected_student = (request.args.get('student_form')).strip()
它的错误:AttributeError: 'NoneType' object has no attribute 'strip'
selected_student.replace(" ", "")
它的错误:AttributeError: 'NoneType' object has no attribute 'replace'
我需要像 trim() 这样的函数,而无需编写 class/subclass 或 javascript
有一个 strip() 方法。您得到的错误是因为您试图在 NoneType 对象上 运行 它。您需要 运行 它在字符串对象上。
>>> s = 'some string '
>>> s.strip()
'some string'
还有字符串替换:
>>> s.replace('some', 'many')
'many string '
您遇到的问题与其他问题有关。您以 None 对象结束,而不是您想要获得的对象。
您看到您看到的错误是因为没有数据 从您的表单传递到 Flask 服务器。您对 request
的使用返回的是 None
值类型,而不是 str
.
您张贴了以下 HTML 表单标记:
<form action="/student" method='POST'>
<select name="student_form ">
{% for student in students_list %}
<option value="{{student}}">{{student}}</option>
{% endfor %}
</select>
<input type='submit' value='submit' />
</form>
因此,您需要在某个地方让 Flask 在服务器端获取这些数据,例如:
@app.route('/student', methods=['POST'])
def receive_student_form_data:
my_selection = str(request.form.get('student_form')).strip()
print(my_selection)
只是为了阐明我以这种方式制作我的方法的原因:我注意到您正在使用 request.args.get()
来检索表单发送的值。这是不正确的。
request.args
用于从 URL.
中检索键/值对
request.form
用于从 HTML 表单中检索键/值对。
所以我建议您改用 request.form.get('student_form')
。如果你真的想确定它在你的 Flask 服务器检索时被转换为 str
,那么你可以将它转换为 str
,如下所示:
str(request.form.get('student_form'))
然后,正如一些人已经建议的那样,您可以使用 .strip()
方法删除任何尾随空格。