检查文本是否以空白开头 space
Check if text starts with blank space
这个问题不是专门针对 django 的,而是 python 整个问题。我想要做的是,当用户提交时,我将如何检查标题是否不应以“”开头 (space)。它可以以任何其他字符开头,但不能以 space 开头。
观看次数:
def admin_page_create(request):
if request.is_ajax() and request.POST:
title = request.POST.get("title", "")
if title != '' or title != <<<regex or function() to check title does not start with a blank space>>>:
Page.objects.create(title=title, user=request.user)
data = "Created a new page: '" + title + "'."
return HttpResponse(json.dumps(data), content_type='application/json')
else:
data = 'You gave us a blank title. Please try again.'
return HttpResponse(json.dumps(data), content_type='application/json')
else:
raise Http404
您可以使用其索引获取字符串的第一个字符,即0
。然后,只需将其与 " "
进行比较或使用 .isspace()
.
if title[0] != " ":
if not title[0].isspace():
如@Andy 和@Daniel 所述,另一个可能更优雅的解决方案是使用 .startswith()
.
if not title.startswith(" "):
您可能对 .strip()
which removes spaces characters from start and end of a string or even .lstrip()
更具体地感兴趣。
您可以使用startswith
方法:
title.startswith(' ')
如果你想检查第一个字符是否是 space:
if title.startswith(" "):
如果你想检查第一个字符是否是白色space,你可以这样做:
import re # regular expression module
if re.match(r"\s", title): # match() matches only at beginning of subject text.
# \s is any whitespace
或者这个:
if title != title.lstrip(): # lstrip removes whitespaces at the left (hence the "l")
这个问题不是专门针对 django 的,而是 python 整个问题。我想要做的是,当用户提交时,我将如何检查标题是否不应以“”开头 (space)。它可以以任何其他字符开头,但不能以 space 开头。
观看次数:
def admin_page_create(request):
if request.is_ajax() and request.POST:
title = request.POST.get("title", "")
if title != '' or title != <<<regex or function() to check title does not start with a blank space>>>:
Page.objects.create(title=title, user=request.user)
data = "Created a new page: '" + title + "'."
return HttpResponse(json.dumps(data), content_type='application/json')
else:
data = 'You gave us a blank title. Please try again.'
return HttpResponse(json.dumps(data), content_type='application/json')
else:
raise Http404
您可以使用其索引获取字符串的第一个字符,即0
。然后,只需将其与 " "
进行比较或使用 .isspace()
.
if title[0] != " ":
if not title[0].isspace():
如@Andy 和@Daniel 所述,另一个可能更优雅的解决方案是使用 .startswith()
.
if not title.startswith(" "):
您可能对 .strip()
which removes spaces characters from start and end of a string or even .lstrip()
更具体地感兴趣。
您可以使用startswith
方法:
title.startswith(' ')
如果你想检查第一个字符是否是 space:
if title.startswith(" "):
如果你想检查第一个字符是否是白色space,你可以这样做:
import re # regular expression module
if re.match(r"\s", title): # match() matches only at beginning of subject text.
# \s is any whitespace
或者这个:
if title != title.lstrip(): # lstrip removes whitespaces at the left (hence the "l")