我有用于检查是否有空间或只是空的代码。我尝试重新制作=,“”,“,==。但是我没有成功。有什么问题?输入密码时,密码总是显示错误,这是我在打印功能中遇到的。
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平台中上传链接。
答案 0 :(得分:0)
您应该使用正则表达式。正则表达式可以检查字符串中的" "
,例如
fontas = password.match(' ')
if fontas:
print('Match found: ', fontas.group())
else:
print('No match')
查看文档以获取更多信息。 https://docs.python.org/3/library/re.html
答案 1 :(得分:0)
fontas
和fontas2
相同,您可以做
if ' ' in password:
print("~ Password can't contain a spaces!\n")
# ...
完整示例:
import getpass
# ...
name = 'Alex' # considering a user called Alex
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 not password:
print("~ Password can't be empty!\n")
continue
else:
break
答案 2 :(得分:0)
我相信这就是您想要的:
if password and (" " in password):
print("BAD")
else
print("GOOD")
首先检查是否有密码,然后检查是否有空格
答案 3 :(得分:0)
要检查提供的字符串是否为空或是否包含空格
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
答案 4 :(得分:0)
我希望这会有所帮助:
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中的字符串是否为空!
一个空字符串将计算为布尔值(假):
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