Home > Software design >  How to check if string contains only valid amount of spaces
How to check if string contains only valid amount of spaces

Time:11-09

I need to write code that checks if a certain input string is valid. It must:

  1. Contain a "space" in the input string which separates words
  2. Not contain multiple consecutive spaces in a row
  3. Not contain just a "space" (just single space as an input).

Here is what I mean:

username = str(input())
print(username)

username = "two apples" # acceptable

username = "two apples and pears" # acceptable

username = "two' '' 'apples" # not acceptable (because of 2 spaces in a row or more)

username = " " # not acceptable (because of single space with no other words.) 

username = "' '' '' '' '' '' '" #not acceptable because of multiple spaces (didn't know how to type it in here better to clarify.

CodePudding user response:

I recognize that this might be slightly different than what you are directly asking for, but why not strip the extra spaces from the username input? You could use regex to quickly strip them out per this answer.

If you simply want to return an invalid input, I would again use regex.

import re

username = str(input("Please enter your username: "))
if re.search(" {2,}", username):
  print("Please do not include multiple spaces in a row in your username!")
else:
  # Do the rest of your program.

CodePudding user response:

I was having my online class, so I couldn't do on time. Now I can give the the answer.

Here's the code. It's pretty simple to understand too.

username = input()
if ("  ") in username:
    print("Eh!")
elif username.isspace():
    print("Ew!")
else:
    print(username)

And BTW you don't need to use str() in the input as it takes a string input by default.

CodePudding user response:

Here is the code you are looking for I believe. Please test with different test cases and comment if something is wrong. I tried with all your test cases.

def checkspace(string):
    if string:
        for idx,i in enumerate(string):
            try:
                if (string[idx] == ' ' and string[idx 1] ==' '):
                    return 'String is Not Perfect'
            except:
                return 'String is Not Perfect'
            
        print('String is Perfect')
    else:
        return 'No String At AlL'

Eg:

string="two apples"
checkspace(string)
  
output:
"String is Perfect"

Eg:

string="two  apples"
checkspace(string)
      
output:
"String is Not Perfect"
     
  • Related