如果userinput字符串为空或数字,或者具有非ascii-Python

时间:2019-03-14 07:23:33

标签: python string alphanumeric

当用户输入名字时,如果它是空白,具有数字或字母数字或具有非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')

2 个答案:

答案 0 :(得分:2)

使用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

EDIT (添加空字符串检查)(即if f_name

答案 1 :(得分:1)

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

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: ')