简体   繁体   English

如何检查输入是否包含 Python 中的特殊字符?

[英]How to check and see if an input contains special characters in Python?

I am a high school programmer currently writing code in Python to strengthen my programming skills and am creating a basic signup page.我是一名高中程序员,目前正在使用 Python 编写代码以增强我的编程技能,并且正在创建一个基本的注册页面。 I want my code to alert the user if their input for a username or password is invalid, but all of the answers I have seen so far are not very helpful.如果用户输入的用户名或密码无效,我希望我的代码提醒用户,但到目前为止我看到的所有答案都不是很有帮助。 I have found "^[a-zA-Z0-9]*$" to be the most useful so far for detecting special characters such as asterisks and periods, but it seems to only work when a user uses all of the characters above instead of just the ones within the range of characters that satisfy the requirement.我发现“^[a-zA-Z0-9]*$”是迄今为止检测星号和句点等特殊字符最有用的方法,但它似乎只在用户使用上述所有字符时才有效满足要求的字符范围内的字符。 I will show my code below:我将在下面展示我的代码:

 while not chosen_user:
     chosen_user = input("""Enter the username that you would like. Please keep it between 6 and 15 
     characters. Do not use special characters such as '&', '@', or '!' in your username. Underscores are allowed.\n>""")
    if (len(chosen_user) >= 6 or len(chosen_user) <= 15) and "^[a-zA-Z0-9_]*$" in chosen_user:
        chosen_user = True
        usernames_passwords[chosen_user] = ''
    else:
        print('Username does not meet the requirements. Please try again.')
        chosen_user = False
 while not chosen_pass:
     chosen_pass = input("""Enter a password that contains no special characters. Password must be at 
        least 6 characters.\n>""")
        if len(chosen_pass) >= 6 and "^[a-zA-Z0-9]*$" in chosen_pass:
            chosen_pass = True
            usernames_passwords[chosen_user] = chosen_pass
        else:
            print('Password is invalid. Please try again.')
            chosen_pass = False

I cannot figure out how to get a password approved while only using some of the characters, and I have been struggling for a while.我无法弄清楚如何在仅使用某些字符的情况下获得密码批准,并且我已经挣扎了一段时间。 Any help would be nice.你能帮忙的话,我会很高兴。

**Also, keep in mind that I am in high school and would prefer to keep this code as simple as possible. **另外,请记住,我在上高中,并且希望此代码尽可能简单。 Imports are okay, but I would like to understand how and when to use these things for future use.进口没问题,但我想了解如何以及何时使用这些东西以备将来使用。 Thanks!!谢谢!!

Try this:尝试这个:

import re #--> import regular expressions module

while not chosen_user:
    chosen_user = input("""Enter the username that you would like. Please keep it between 6 and 15
    characters. Do not use special characters such as '&', '@', or '!' in your username. Underscores are allowed.\n>""")
    if (len(chosen_user) >= 6 and len(chosen_user) <= 15) and re.search(r"^[A-Za-z0-9_]+$", chosen_user):
        chosen_user = True
        usernames_passwords[chosen_user] = ''
    else:
        print('Username does not meet the requirements. Please try again.')
        chosen_user = False

while not chosen_pass:
    chosen_pass = input("""Enter a password that contains no special characters. Password must be at 
    least 6 characters.\n>""")
    if len(chosen_pass) >= 6 and re.search(r"^[A-Za-z0-9_]+$", chosen_pass):
        chosen_pass = True
        usernames_passwords[chosen_user] = chosen_pass
    else:
        print('Password is invalid. Please try again.')
        chosen_pass = False

You can simplify your looping logic and also your string checking by using regular expressions:您可以使用正则表达式简化循环逻辑以及字符串检查:

import re

chosen_user = input("""Enter the ... allowed.\n>""")
while not re.match(r"^\w{6,15}$", chosen_user, flags=re.ASCII):
    chosen_user = input('Username does not meet the requirements. Please try again.')

chosen_pass = input("""Enter a password ... least 6 characters.\n>""")
while not re.match(r"^[a-zA_Z]{6,}$", chosen_pass):
    chosen_pass = input('Password is invalid. Please try again.')

You will find in the re docs :你会在re docs 中找到:

"^"
(Caret.) Matches the start of the string, and in MULTILINE mode also matches immediately after each newline. (Caret.) 匹配字符串的开头,并且在 MULTILINE 模式下也匹配紧接在每个换行符之后。

"$"
Matches the end of the string [...].匹配字符串 [...] 的结尾。

"\\w"
Matches Unicode word characters;匹配 Unicode 单词字符; this includes most characters that can be part of a word in any language, as well as numbers and the underscore.这包括可以成为任何语言中单词一部分的大多数字符,以及数字和下划线。 If the ASCII flag is used, only [a-zA-Z0-9_] is matched.如果使用 ASCII 标志,则仅匹配 [a-zA-Z0-9_]。

"{m,n}"
Causes the resulting RE to match from m to n repetitions of the preceding RE, attempting to match as many repetitions as possible.导致生成的 RE 匹配前面 RE 的 m 到 n 个重复,尝试匹配尽可能多的重复。 For example, a{3,5} will match from 3 to 5 'a' characters.例如,a{3,5} 将匹配 3 到 5 个“a”字符。 Omitting m specifies a lower bound of zero, and omitting n specifies an infinite upper bound.省略 m 指定下限为零,省略 n 指定无限上界。

 while not chosen_user:
     chosen_user = input("""Enter the username that you would like. Please keep it between 6 and 15 
     characters. Do not use special characters such as '&', '@', or '!' in your username. Underscores are allowed.\n>""")
    if (len(chosen_user) >= 6 or len(chosen_user) <= 15) and "^[a-zA-Z0-9_]*$" in chosen_user:
        chosen_user = True
        usernames_passwords[chosen_user] = ''
    else:
        print('Username does not meet the requirements. Please try again.')
        chosen_user = False
 while not chosen_pass:
     pas = input("""Enter a password that contains no special characters. Password must be at 
        least 6 characters.\n>""")
        schar="@_!#$%^&*()<>?/\|}{~:]"
        if len(pas)>=6:
           for i in pas:
               if i in schar:
                   choosen_pass=True
                   break
            usernames_passwords[chosen_user] = chosen_pass
        else:
            print('Password is invalid. Please try again.')
            chosen_pass = False

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 检查字符串是否包含python中的特殊字符 - check if string contains special characters in python Python如何检查输入是否仅包含某些字符? - Python how to check if an input only contains certain characters? 检查字符串何时只包含python中的特殊字符 - Check when string contains only special characters in python 如何检查python中特殊字符的表单项? - How to check form entry for special characters in python? 如何检查一个字符串是否包含另一个被特殊字符包围的字符串? - How to check if a string contains another string surrounded by special characters? python如何从用户输入中检查不包括数字和特殊字符的数据 - How python check data from user input that not include number and special characters 如何使用python 3检查文件夹是否包含文件 - How to check to see if a folder contains files using python 3 如果 Python 中有特殊字符,如何使用循环拒绝用户输入 - How to Reject User Input with Loop if it has Special Characters in Python 如何使用正则表达式搜索字符串以查找包含字母,特殊字符(如-,())的字符串(使用python) - How to search string using regular expression for string contains characters alphabets and special characters like -, () using python 如何检查字符串是否只包含python中给定集合的字符 - How to check if a string contains only characters from a given set in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM