I need to write code that checks if a certain input string is valid. It must:
Contain a "space" in the input string which separates words
Not contain multiple consecutive spaces in a row
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.
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.
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.
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
I am looking to ask the user to input their first and last name and validate it so that it is only alphabetical letters and spaces and then add it to a text file.
**This is the edited code from your suggestions and it always returns the first print message even though letters have been entered
while True:
new_Book_AuthorFName = input('Enter Author First Name: ')
new_Book_AuthorLName = input('Enter Author Last Name: ')
new_Book_Author_Name = new_Book_AuthorFName + " " + new_Book_AuthorLName
try:
new_Book_Author_Name.replace(' ', '').isalpha()
print("Please Only Use Alphabetical Characters in Name.")
continue
break
except ValueError:
print("Invalid Name.")
Something like this should work:
def include_letter_and_spaces_only(string):
return "".join(string.split(" ")).isalpha()
And then use as:
include_letter_and_spaces_only("test Test Test") # True
include_letter_and_spaces_only("test 12 Test Test") # False
I would do this as.
def lettersOnly(theString: str) -> bool:
"""Determine if a string only contains letters and spaces or not."""
return ''.join(
theString.split(' ')
).isalpha()
Simplest and most pythonic way to be:
def is_alpha_and_spaces_only(string):
return string.replace(' ', '').isalpha()
Faster and more efficient than KetZoomer's approach as it does not require you to (a) split string & (b) combine it back to have result.
P.S. Or just the spirit of the function if you dont want to define that. Just use new_Book_Author_Name.replace(' ', '').isalpha() inplace of if not new_Book_Author_Name.isalpha()
I am trying to write a function that checks for a strong password. The password must contain one upper case, one lower case,a number and must be 8 characters long.
import re
def checker():
while True:
userInput = input(' Please input a password ')
passwordRegex = re.compile(r'[a-zA-Z0-9]+ {,8}')
match = passwordRegex.search(userInput)
if match:
print('Good!')
else:
print('Bad!')
checker()
This function always outputs Bad even when the password meets all the requirements. I have a feeling the error has to do with how I am using my Regex and Variables. I am using python 3.6.
Expanding on the answer from here:
passwordRegex = re.compile("^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])\S{8,}")
check out this demo
Using lookaheads we make sure there is at least one character from each group, then require at least 8 characters total. Note that you can customize the allowed characters (if you want to allow symbols) by changing the last group, the one before {8,}
Based on the feedback from #Aran-Fey and #Tomerikoo, i have updated my code and it works now.
import re
def checker():
while True:
userInput = input(' Please input a password ')
passwordRegex = re.search(r'^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$',userInput)
if passwordRegex:
break
print('Good!')
checker()
I am writing a program which is like an email validator, the user enters their email and then the program checks it has the necessary components. I have to check it contains an # sign. I want to split the email character by character and put it into a list so that I can loop through the list to get the email.
I currently have this:
email=input('Please enter your email address: ')
mylist=[]
mylist(email)
for i in mylist:
if i != '#':
at=True
print('Your email is invalid because it does not contains an # sign.')
There is no need to convert a string into a list in order to iterate over it.
In Python, a string is already iterable, so you can do:
for c in email:
if c != '#':
print(...)
But Python offers you a better construct, the in operator:
if '#' not in email:
print(...)
You can just do
if '#' not in email:
print('Your email is invalid because it does not contains an # sign.')
If you just need to check if a string has a character inside, you can use:
if char in string:
So in your case:
if '#' in email:
print("This appears to be a valid email.")
You can easily use regex to archive what you want
list = ['email#emailprovider.com', 'not_an_email']
for email in list:
if not re.match('(^[a-zA-Z0-9_.+-]+#[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)', email):
print('Your email ({}) is invalid because it does not contains an # sign.'.format(email))
In Python strings are already iterable. So, you can use the following code to achieve what you want.
email = input("Enter your email")
if '#' not in email:
print("The email is invalid as it does not contains #.")
else:
print("valid email")
Why don't you use python-regex?
It is relatively fast.
put this in if clause :-
for i in mylist:
email_addr = re.search(r"(^[a-zA-Z0-9_.+-]+#[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)", i)
if email_addr:
print email_addr.group()
else:
print 'incorrect format'
and retreive the address using email_addr.group()
and you are good to go.enter code here
I am trying to write a function that checks my input to see whether I have entered the character '?'.
This is what I got so far:
def check_word():
word = []
check = 0
user_input = input('Please enter a word that does not contain ?: ')
for token in user_input.split():
if token == '?':
print('Error')
check_word()
My input: hello?
It is supposed to show 'Error'. But it doesn't show anything. Could you please tell me what wrong it is in my code.
I would use the in operator to do this
def check_word(s):
if '?' in s:
print('Error')
For example
>>> check_word('foobar')
>>> check_word('foo?')
Error
The problem is how you split the string of the user_input.
user_input.split():
The example doesn't contain whitespaces so the condition isn't met. If you want for example to check a sentence with spaces, you should split it like this: user_input.split(' ') to split it on the spaces.
But for this example you have two choices:
1) You can just iterate over the input itself because you want to check every char in the string for whether it's a ?.
That is, change user_input.split(): into simply user_input without splitting. This option is good if you might ever want to add some sort of action for each char.
2) It's very easy just to use in, like this:
if '?' in s:
print('There is a question mark in the string')
This is a very simple solution that you can expand and check for other chars in the string as well.
It's because user_input.split() splits the user_input by whitespace. Since hello? does not contain any whitespaces, token is equal to your input and the loop is executed once.
You should iterate over user_input instead, or simply check if '?' in user_input.
so I'm quite new to programming and I'm trying to learn python as a starter.
I'm trying to make a function that does multiple things (I'm going to use it for limiting inputs on names).
Rejects purely numerical inputs
Rejects inputs made purely of spaces
Rejects null inputs
Changes the input into a title
def debugstr(inputa):
inputa = inputa.replace(" ", "")
try:
int(inputa)
inputb = debugstr(input("Invalid input, please enter Alphabetic strings only: "))
except:
if inputa == "":
debugstr(input("Invalid input, please enter Alphabetic strings only: "))
else:
return inputa.title()
The issue that I have is that the code will only reject blank inputs on the first try when running the function, if something is rejected once and the user inputs a series of spaces again, then it will just accept it as an input.
Thanks for your time in advance! It's very appreciated :D
A more natural way of handling this (without calling the same function from within itself) is:
def make_title():
def get_user_input():
return input('Enter an alphabetic string: ')
while True:
s = get_user_input()
s = s.strip()
if not s:
print('blank input!')
continue
if s.isdigit():
print('contains only digits!')
continue
return s.title()
print(make_title())
Some notes:
Try not to repeat yourself (e.g. the duplicated error message in your code)
Python contains many useful string methods and s.isdigit() returns True if s contains only numbers
You can strip the whitespace from your input with s.strip() and if you're left with the empty string, '', if not s will be True (the empty string is equivalent to False.
In python 3, you can use isinstance to check if an object is a string.
word = input("Enter string: ")
def checkString(s):
if isinstance(s, str):
print('is a string')
elif not s:
print('empty')
else:
print('not a string')