社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

如果用户输入字符串为空、数字或具有非ASCII python

Sheikh Rahman • 6 年前 • 1456 次点击  

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

下面的代码不接受有效输入,只有使用 len isDigit 这两个条件。

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')
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/38489
 
1456 次点击  
文章 [ 2 ]  |  最新文章 6 年前