简体   繁体   中英

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

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

So, if I understand you correctly you don't want ANY spaces in the string? strip() just removes the spaces at the start and end, if you want to remove all spaces in a string you would use something like the replace method. Replace will remove all occurrences of a character and replace them with another (an empty string in this case).

Example:

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

main()

This code will output "HelloWorld!"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM