字符串输入中不允许有空格 Python
Not allowing spaces in string input Python
我试图在输入的字符串中不允许任何字符串。我试过使用 len strip 来尝试计算空格并且不允许它但它似乎只计算初始空格而不是输入字符串之间的任何空格。
此代码的 objective 是:输入不允许空格。
当真:
try:
no_spaces = input('Enter a something with no spaced:\n')
if len(no_spaces.strip()) == 0:
print("Try again")
else:
print(no_spaces)
except:
print('')
那么,如果我的理解正确的话,您不需要字符串中有任何空格? strip() 只是删除开头和结尾的空格,如果你想删除字符串中的所有空格,你可以使用类似 replace 的方法。替换将删除所有出现的字符并将其替换为另一个字符(在本例中为空字符串)。
示例:
def main():
myString = "Hello World!"
noSpaces = myString.replace(" ", "")
print(noSpaces)
main()
此代码将输出“HelloWorld!”
此代码只接受没有空格的输入。
no_spaces = input('Enter a something with no spaces:\n')
if no_spaces.count(' ') > 0:
print("Try again")
else:
print("There were no spaces")
双选
while True:
no_spaces = input('Enter a something with no spaces:\n')
if no_spaces.find(' ') != -1:
print("Try again")
else:
print("There were no spaces")
break
或者
while True:
no_spaces = input('Enter a something with no spaces:\n')
if ' ' in no_spaces:
print("Try again")
else:
print("There were no spaces")
break
我试图在输入的字符串中不允许任何字符串。我试过使用 len strip 来尝试计算空格并且不允许它但它似乎只计算初始空格而不是输入字符串之间的任何空格。 此代码的 objective 是:输入不允许空格。
当真:
try:
no_spaces = input('Enter a something with no spaced:\n')
if len(no_spaces.strip()) == 0:
print("Try again")
else:
print(no_spaces)
except:
print('')
那么,如果我的理解正确的话,您不需要字符串中有任何空格? strip() 只是删除开头和结尾的空格,如果你想删除字符串中的所有空格,你可以使用类似 replace 的方法。替换将删除所有出现的字符并将其替换为另一个字符(在本例中为空字符串)。
示例:
def main():
myString = "Hello World!"
noSpaces = myString.replace(" ", "")
print(noSpaces)
main()
此代码将输出“HelloWorld!”
此代码只接受没有空格的输入。
no_spaces = input('Enter a something with no spaces:\n')
if no_spaces.count(' ') > 0:
print("Try again")
else:
print("There were no spaces")
双选
while True:
no_spaces = input('Enter a something with no spaces:\n')
if no_spaces.find(' ') != -1:
print("Try again")
else:
print("There were no spaces")
break
或者
while True:
no_spaces = input('Enter a something with no spaces:\n')
if ' ' in no_spaces:
print("Try again")
else:
print("There were no spaces")
break