【问题标题】:If userinput String is empty or numeric or has non ascii-Python如果用户输入字符串为空或数字或非 ascii-Python
【发布时间】:2019-03-14 07:23:32
【问题描述】:

当用户输入名字时,如果它是空白的、有数字或字母数字或有非 ascii 字符,我不会将其插入数据库。

下面的这段代码不接受有效输入,只有当我使用lenisDigit 这两个条件时它才有效。

while (len(f_name) == 0  or f_name.isdigit()

f_name.encode('ascii',errors='ignore') or f_name.isalnum()):
Create new user: Y/N ?y
Enter first name: ui
First name cannot be empty or have numeric values

谁能解释一下如何解决这个问题?谢谢你的时间。其余代码如下:

import sqlite3

#connect a built in function to connect or create db
conn=sqlite3.connect('phonebook.db')

#Create a cursor function which allows us to do sql operations
crsr=conn.cursor()

#This function to check if table exists
def create_Table():
    #Check if the table exists or not
    crsr.execute("SELECT name FROM sqlite_master WHERE name='phonebook'")
    tableSize=len(crsr.fetchall())#will be greater than 0 if table exists
    if tableSize>0:
        print()
    else:
        #create the table
        crsr.execute(""" Create Table phonebook(
                    FirstName text NOT NULL,
                    LastName text,
                    Phone text PRIMARY KEY NOT NULL)
                   """)

        #check if table got created or not
        crsr.execute("SELECT name FROM sqlite_master WHERE name='phonebook'")
        tableSize = len(crsr.fetchall())  # will be greater than 0 if table exists
        if tableSize > 0:
            print('Table was created successfully')

#This function will create new users and insert in DB
def create_User():
    try:
        while True:
            rsp = input('Create new user: Y/N ?')
            if rsp == 'y':
                f_name = input('Enter first name: ')
                # First name cannot be empty or have numeric values
                while (len(f_name) == 0  or f_name.isdigit() or f_name.encode('ascii',errors='ignore') or f_name.isalnum()):
                    print('First name cannot be empty or have numeric values')
                    f_name = input('Enter first name: ')
                l_name = input('Enter last name: ')
                phone = input('Enter phone number: ')
                crsr.execute("INSERT INTO phonebook VALUES (:FirstName, :LastName, :Phone)",
                             {'FirstName': f_name, 'LastName': l_name, 'Phone': phone})
                conn.commit()
            if rsp == 'n':
                break
    except:
     print('UNIQUE constraint failed: phone number already exists')

【问题讨论】:

  • 你能给我们举个例子,说明哪个用户名目前确实被接受但不应该被接受吗?
  • James,Amy 应该被接受,但不是 2345 或 Am4y 或 Am$anda。谢谢
  • 条件:f_name.isalnum() 将是 True 名称 "ui"
  • 这似乎相关:kalzumeus.com/2010/06/17/…

标签: python string alphanumeric


【解决方案1】:

使用isalpha 确保字符串只有字母:

f_name = input('Enter first name: ')
if f_name and f_name.isalpha():
  # your ACCEPTED logic here

此外,如果您需要检查这些字母是否为 ASCII,您可以巧妙地将它们的编码长度与它们自己进行比较:

f_name = input('Enter first name: ')
if f_name and f_name.isalpha() and len(f_name) == len(f_name.encode()):
  # your ACCEPTED logic here

编辑添加空字符串检查(即if f_name

【讨论】:

  • 如果 OP 不想使用整个 unicode 范围作为名称(出于什么原因),他应该可以丢弃其他合法名称。
  • @Serge 现在已经看到 OP 的评论了。我可以为, 添加一个额外的条件,但我更喜欢等待完整的条件被声明。也许. 也被接受了,谁知道呢。或者逗号本身不会被接受,等等。必须澄清。
  • 很好的讨论,很抱歉,如果我没有正确阐明所有要求。这个讨论给了我更多的测试想法。
【解决方案2】:

如果您对正则表达式感到满意,您可以通过以下方式测试“不得为空”和“不得包含数字”的条件:

import re

# match one or more characters that range from a to z or A to Z
username_check = re.compile(r'[a-zA-Z]+')

...
while True:
  if rsp == 'y':
    f_name = input('Enter first name: ')
    while not username_check.fullmatch(f_name):
      print('First name cannot be empty or have numeric values')
      f_name = input('Enter first name: ')

正则表达式的好处是您可以非常灵活地扩展当前的最小解决方案,以测试非常具体的模式:

import re

# allow unicode word characters
allowed = re.compile(r'\w+')
# numbers are still not allowed
forbidden = re.compile(r'\d')

while True:
    f_name = input('Enter first name: ')
    while not (allowed.fullmatch(f_name) and not forbidden.search(f_name)):
      print('First name cannot be empty or have numeric values')
      f_name = input('Enter first name: ')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-11
    • 1970-01-01
    • 2013-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-11
    相关资源
    最近更新 更多