输入为空

2024-10-04 07:39:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我有代码检查是否有任何空间或它只是空的。我试着重新制作=,“”,“”,==。但我没有成功。有什么问题吗?当我输入密码时,它总是显示错误,这是我在打印功能。你知道吗

while True:
    password = getpass.getpass("~ Please pick a password, for user - {n}\n".format(n=name))
    fontas = " "
    fontas2 = ' '
    if fontas and fontas2 in password:
        print("~ Password can't contain a spaces!\n")
        continue
    else:
        break

编辑* 我正在添加一个GIF。当我稍微修改了一段代码时,这就向你展示了它是如何工作的。你知道吗

第一次我试着做一个空格,之后我什么都没打,最后一次我把普通的关键字-ffawt

*我不能添加GIF文件,所以我正在Gyazo平台上传链接。你知道吗

链接-enter link description here


Tags: 代码功能true密码链接错误空间password
3条回答

要检查提供的字符串是否为空,或是否包含任何空格,请执行以下操作

while True:

    password = getpass.getpass("~ Please pick a password, for user {n}\n".format(n=name))
    fontas = " "
    if fontas in password:
        print("~ Password can't contain a spaces!\n")
        continue
    elif password == '':
        print("~ Password cannot be empty!\n")
        continue
    else:
        break

你应该使用正则表达式。正则表达式可以检查字符串中的" "

fontas = password.match(' ')
if fontas:
    print('Match found: ', fontas.group())
else:
    print('No match')

查看文档以了解更多信息。 https://docs.python.org/3/library/re.html

我希望这有助于:

while True:
    Password = input('Enter a password: ')
    if " " in Password or len(Password) == 0:
        print("~ Password can't contain a spaces!")
        continue

    #if 'if' statement evaluates to True
    print(Password)
    break

编辑:

尽管这将“完成任务”,但在python中还有其他方法可以计算字符串是否为空!你知道吗

空字符串将计算为布尔值(False):

Password = ""
if not Password:
      print("isempty")
>>> isempty

也就是说,上面的代码可以重构为:

while True:
      Password = input('Enter a password: ')
      #Make 'falsy' evaluation of password
      if not Password or " " in Password:
          print("~ Password can't contain a spaces!")
          continue

     #if 'if' statement evaluates to True
      print(Password)
      break

相关问题 更多 >