不允许在字符串输入 Python 中使用空格

问题描述

我试图在输入的字符串中不允许任何字符串。我试过使用 len strip 来尝试计算空格并且不允许它但它似乎只计算初始空格而不是输入字符串之间的任何空格。 这段代码的目的是:输入不允许空格。

虽然为真:

  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('')

解决方法

此代码只接受没有任何空格的输入。

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
,

所以,如果我理解正确,您不希望字符串中有任何空格? strip() 只是删除开头和结尾的空格,如果您想删除字符串中的所有空格,您可以使用类似 replace 方法的方法。 Replace 将删除所有出现的字符并将它们替换为另一个(在这种情况下为空字符串)。

示例:

def main():
    myString = "Hello World!"
    noSpaces = myString.replace(" ","")
    print(noSpaces)

main()

此代码将输出“HelloWorld!”