我需要验证一个名称,不使用正则表达式并保持简单,我有以下代码:
def validation(name):
for char in name:
if not (("A" <= char and char <= "Z") or ("a" <= char and char <= "z") or (char == " ")):
return False
return True
有没有办法使它变得更好?
我需要验证一个名称,不使用正则表达式并保持简单,我有以下代码:
def validation(name):
for char in name:
if not (("A" <= char and char <= "Z") or ("a" <= char and char <= "z") or (char == " ")):
return False
return True
name = "oridm"
if name.replace(" ", "").isalpha():
print "Name is valid"
else:
print "Name is invalid"
有一个有用的列表string.letters
,其中包含所有英文字母,因此您的代码可以写成一行:
import string
all(c in string.letters + ' ' for c in name)
+ ' '
。 - myautimport re
pattern = re.compile(r'([a-zA-Z])\D*([a-zA-Z])$')
pattern.search('string you're searching')
这个 - 或者类似的东西 - 将允许您解析字符串。它查找第一个字符串,然后忽略非数字的可选分隔符(\D*),然后是最终的字符串。
=
:-) - thiruvenkadamimport re
def validate_user(username, minlen):
"""Checks if the received username matches the required conditions."""
if type(username) != str:
raise TypeError("username must be a string")
if minlen < 1:
raise ValueError("minlen must be at least 1")
# Usernames can't be shorter than minlen
if len(username) < minlen:
return False
# Usernames can only use letters, numbers, dots and underscores
if not re.match('^[a-z0-9._]*$', username):
return False
# Usernames can't begin with a number
if username[0].isnumeric():
return False
return True
^[a-zA-Z]$
完成 - vksif char == ' ' or ("A" <= char <= "Z") or ("a" <= char <= "z") continue; else: return False
。 - thiruvenkadam