Search code examples
pythonif-statementwhile-loopexcept

Not allowing spaces in string input Python


I am trying to not allow any strings whatsoever in the inputted string. I've tried using len strip to try and count the whitespaces and no allowing it but it seems to only count the initial whitespaces and not any in between the inputted string. the objective of this code is: input will not allow spaces.

while True:

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

Solution

  • This code will only accept inputs that don't have any spaces.

    no_spaces = input('Enter a something with no spaces:\n')
    if no_spaces.count(' ') > 0:
        print("Try again")
    else:
        print("There were no spaces")
    

    double alternatively

    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
    

    alternatively

    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