Separating characters of a string into a list (python) - python

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

Related

How to check if string contains only valid amount of spaces

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"

user input can only be alphabetical characters and includes spaces

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

Python: How to demand a string as input rather than a specific value

For the YourName input() I would like to get a value that's a string. Hence, it shouldn't be a float, int, etc. In this example I would like to replace "Sunny" with any value that's a string to make the while loop accept the input.
YourName = ''
while YourName != "Sunny":
print("Please type in your name")
YourName = input()
print(YourName + " is correct")
Thanks in advance, best
Sentino
As mentioned in the comments you could use something similar to the following:
YourName = input("Please enter your name: ")
while True:
if YourName.isalpha():
break
else:
print("Must enter string")
print("Please type in your name")
YourName = input("Please enter your name: ")
continue
isinstance() is a built-in function that checks to see if a variable is of a specific class, e.g. isinstance(my_var, str) == True. However, the Input() function always returns a string. Thus, if you want to make sure the input was all letters you want to use .isalpha(). You could also use Try/except. As #SiHa said this SO question has a great response.
As pointed out in the comments, this answer will not work if there is a space in the string. If you want to allow multiple name formats you can use Regex. for example you can do the following:
import re
YourName = input("Please enter your name: ")
while True:
if re.fullmatch(r"[a-zA-Z]+\s?[a-zA-Z]+", YourName) is not None:
break
else:
print("Must enter string")
print("Please type in your name")
YourName = input("Please enter your name: ")
continue
Using Regular Expressions will give you more control on the inputs than regular string methods. Docs, Python Regex HOWTO. re is a standard library that comes with python and will give you the most flexibility. You can use regex101 to help you test and debug.
What the re.fullmatch() will return a match object if found and None if not. It says the input can be any lower or uppercase letter with an optional space in the middle followed by more letters.
If you don't want to import a package then you can loop through your input object and check to see if all characters are a space or alpha using:
all([x.isalpha() | x.isspace() for x in YourName])
however this will not say how many spaces there are or where they are. It would be optimal to use Regex if you want more control.
It's possible that you're using Python 2.7, in which case you need to use raw_input() if you want to take the input as a string directly.
Otherwise, in Python 3, input() always returns a string. So if the user enters "3#!%," as their name, that value will be stored as a string (You can check the type of a variable by using type(variable)).
If you want to check to make sure the string contains only letters, you can use the method isalpha() and isspace() (in my example code, I'll assume you want to allow spaces, but you can exclude that part if you want to require one word responses).
Because these methods operate on characters, you need to use a for loop:
YourName =""
while YourName is not "Sunny" or not all(x.isalpha() or x.isspace() for x in YourName):
#You can pass a string as a prompt for the user here
name = input("please enter name")
print (YourName)
However, I should note that this check is totally redundant since no string containing a non-letter character could ever be equal to "Sunny".
As others have pointed out, input() always returns a string.
You can use the str.isalpha method to check the character is a letter.
YourName = ''
while True:
print("Please type in your name")
YourName = input()
failed = False
for char in YourName:
if not char.isalpha():
failed = True
if not failed:
break
Example:
Please type in your name
> 123
Please type in your name
> John1
Please type in your name
John
John is correct

Changing inputs into titles, issue with handling raw spaces

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

Password Tester in Python [duplicate]

This question already has answers here:
can this code be shortened or improved? [closed]
(3 answers)
Closed 9 years ago.
I am writing a program that is supposed to take a string (the password entered by user) and test it to make sure it meets the following requirements:
must contain at least one uppercase letter and one lowercase letter
must start with a letter
minimum of eight characters
no blanks
must contain at least two digits
this is what i have so far and I'm stuck getting invalid syntax errors
running = True
while running:
valid = 0
password = str("Enter Password: ")
if len(p) <8:
print ("The password you entered is too short. Please try again.")
running = False
import re
#check if contains a digit
if re.search(r '\d', password):
password = valid
#check if contains uppercase letter
if re.search(r '[A-Z]', password):
password = valid
#check if contains lowercase letter
if re.search(r '[a-z]', password):
password = valid
#check if contains only letters
if re.search(r "[a-z]", password) and re.search(r "[A-Z]", password):
print ("Password must contain at least 2 digits. Please try again.")
#check if contains all lowercase letters
if password.islower():
print ("Password must contain at least 1 uppercase letter. Please try again.")
#check if contains all uppercase letters
if password.isupper():
print ("Password must contain at least 1 lowercase letter. Please try again.")
if password == valid:
print ("Valid Password")
There are multiple problems with the code shown, in addition to the spacing error in your regexps, as mentioned by DevEight.
1) password = str("Enter Password: ") - this does not ask the user for a password, this sets the name password to refer to the string "Enter Password: ". You want input instead (or raw_input for Python version 2.x).
2) if len(p) <8: - p is not a defined name. Presumably you mean password.
3) running = False - this is the only place you set this variable, but it controls your while loop. Your loop only exits when this is false, so this will keep looping until the password is too short, whereup it will eventually exit.
4) password = valid - this sets the password name to refer to the contents of the variable valid, which you initialize to 0. You then run further regular expression searches against the integer 0, which are of course wrong.
5) if re.search(r "[a-z]", password) and re.search(r "[A-Z]", password): - this is commented to say that it requries that there be at least two numbers in the password. It doesn't. I have no idea why you might think it does.
6) if password == valid: - this kind of sort of works, in the sense that you may have previously set password to have the same value as valid. As mentioned above, that's wrong, but it means this could sometimes return True. With working code, you need completely different logic.
7) To top it all off, your question refers to syntax errors from running = True - but that assignment isn't present anywhere in the code.
On the up side, good use of isupper and islower. Those methods make your earlier upper and lowercase regexp searches unnecessary.
You don't seem to get the password from the user.
password = str("Enter the password")
should be:
password = raw_input("Enter the password")
Then, you are checking for valid conditions, which may cause logical errors. So, instead of checking if it satisfies all conditions, check if it does not satisfy any condition (ie) reverse of what you are doing right now..
Eg)
flag = 1
invalid = 0
if(len(password)<8):
flag = 0
if password.islower():
flag = 0
#all conditions
#at last, check for the flag value.
if flag:
print "Password valid"
else:
print "Password not valid"

Categories