how to check last characters of a string - python

I'm trying to make a program that only accepts valid email addresses without using anything super fancy. I'm trying to use negative indexing to get the last characters of the string the user enters and make sure the input is valid. I can't seem to figure out how to check the last characters of the string using this method. Here's what I have so far:
email = 'None'
while email != '#gmail.com':
email = input("Please enter your email. It must be a valid Gmail email: ")
if '#gmail.com' in email[-11:0]:
continue
else:
print("Enter a valid Gmail email.")
I've tried rearranging the values in the index and changing the values themselves, but no matter what it always says to enter a valid email even if it does end in #gmail.com. I'm not trying to allow any valid email, I only care about Gmail emails so I need to work for this only.

str='abc#gmail.com'
sliced_str=str[-10:]
this gives a string with last 10 chars in string. But a better approach would be to use endswith() function like this:
if str.endswith("#gmail.com")
you also need to check if the user input has multiple #'s as well. SO, to consider both you can do something like this:
if str.count('#')==1 and str.endswith("#gmail.com")
To address the comments, you can create a simple function like this to check the mail address like this:
def check_mails(mail_address, dom_list):
for i in dom_list:
if mail_address.endswith(i):
return True
return False
and in your if condition :
if str.count('#')==1 and check_mails(str, ['#yahoo.com', '#gmail.com', '#hotmai.com'])
for checking if the user has intput only '#gmail.com' you can do that with the size of string like this: (considering an email has at least 3 characters before domain name)
if str.count('#')==1 and len(str)>=13 and str.endswith("#gmail.com")

You can use endswith:
if email.endswith("#gmail.com"):

If you want to stick with negative indexing, you need to get rid of the 0. Also, you only need the last 10 characters to match '#gmail.com'. This should work better: email[-10:].
In email[-11:0], the 0 after the colon makes it try to match all characters whose indices are greater than or equal to the length of the string minus 11, and also less than 0. There aren't any indices in that range, so it won't match anything.

Related

Am I able to use the function 'count()' to find the amount of upper cases in a password? (PYTHON)

When I enter the code below, it says:
TypeError: must be str, not list
Does this mean I cannot use the function count() or is there another way I could program it?
password = "CheeseMakesMeHappy"
uppercase =["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
print (password.count(uppercase))
Just go through every character in the password and check if it is an uppercase character.
For example:
password = "FoOoObA"
print(len([c for c in password if c.isupper()]))
>> 4
Another method is using sets and bitmasks to count the number of unique uppercase characters.
password = "CheeseMakesMeHappy"
uppercase = set(["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"])
print(len(set(password)&uppercase))
>> 3
The set solution however will only count UNIQUE characters, but in the case of password strength metering that might not be a bad idea.
The problem is that the method count() expects a string object. Right now, with this line (password.count(uppercase)), you are effectively passing an Array object to your function. See zeraien's answer for a good solution.

If I have a variable in Python 2 with a string in it, how can I split this into several variables each with one character in?

The idea is, a user inputs an identification code, and, to check whether it meets a certain letter/number format, and that prohibited characters are not used in certain positions, each character is in its own variable.
number = input("What is your identification number?")
if first character is a letter:
append to list
else:
if first character number:
et cetera
First, in Python 2, input() does evaluation. To get a string, user should enter something in string syntax. E.g., input
"1234"
results in string "1234", but
1234
results in number 1234. It seems to me you need raw_input() instead. But you should notice Python3 doesn't evaluate, its input is equivalent to Python2 raw_input.
After this correction, you would get a string. If number is its variable name, number[0] is the very first character, number[1] is the second one, and so on.
I also suggest doing strip() on the string before analyzing it, because it's too typical for users to enter insignificant spaces before or after the real value.

Python "SyntaxError: invalid token" on numbers starting with 0 (zeroes)

I know someone might think this question has been answered here but it doesn't have answer to what I want to achieve.
I have list of phone numbers, a very large one, and a whole lot of them starts with 08 and there is a lot of duplication, which is what I am trying to remove. Now I need to put them in a list or set so that I can use them in my program but it returns Invalid token as shown in the picture below:
Python assumes anything that starts with 0 as octal. How do I device a mean to bypass this and have these numbers in a list and then in a set?
read your phone input file, save each phone as string to a set, then the duplicates will be removed due to set only hold unique elements, and you can do further work on them.
def get_unique_phones_set():
phones_set = set()
with open("/path/to/your/duplicated_phone_file", "r") as inputs:
for phone in inputs:
# phone is read as a string
phones_set.add(phone.strip())
return phones_set
If you need to have them prepended by 08, use strings instead of ints.
a = ["08123","08234","08123"]
a = list(set(a)) # will now be ["08123","08234"]
Since (as you say) you don't have an easy way of surrounding the numerous numbers with quotes, go to http://www.regexr.com/ and enter the following:
Expression: ([0-9]+)
Text: Your numbers
Substitution (expandable pane at the bottom of the screen: "$&"

python idle how to create username?

Write a function called getUsername which takes two input parameters, firstname (string) and surname (string), and both returns and prints a username made up of the first character of the firstname and the first four characters of the surname. Assume that the given parameters always have at least four characters.
First, you will want to make a function. (Please note any syntax I use will be for V2.7)
def makeUsername(firstName,lastName):
Next, I would suggest a string to store the username that you will make. You only want the first character and then the first 4. Note the first and last names will be whatever you name the parameters.
x = firstName[0] + lastName[:4]
Finally, printing the string and returning the string.
print x
return x
Then, when you call the function it will look something like this:
makeUsername('John', 'Smith')
If you have any more questions, just ask!
This is how you build the string: firstname[0] + surname[:4]

How can I check if the users input is a number?

I'm trying to create a function to check if the user inputs a number. If the user inputs a number my program should output an error message, if the users enters a string of letters, my program should proceed with program. How can I do this?
I've come up with this so far:
#Checks user input
def CheckInput():
while True:
try:
city=input("Enter name of city: ")
return city
except ValueError:
print ("letters only no numbers")
This function doesn't seem to work. Please help.
You are looking to filter out any responses that include digits in the string. The answers given will do that using a regular expression.
If that's all you want, job done. But you will also accept city names like Ad€×¢® or john#example.com.
Depending on how choosy you want to be, and whether you're just looking to fix this code snippet or to learn the technique that the answers gave you so that you can solve the next problem where you want to reject anything that is not a dollar amount, say),you could try writing a regular expression. This lets you define the characters that you want to match against. You could write a simple one to test if the input string contains a character that is not a letter [^a-zA-Z] (the ^ inside [ ] means any character that is not in the class listed). If that RE matches, you can then reject the string.
Then consider whether the strict rule of "letters only" is good enough? Have you replaced one flawed rule (no digits allowed) with another? What about 'L.A.' as a city name? Or 'Los Angeles'? Maybe you need to allow for spaces and periods. What about hyphens? Try [^a-zA-Z .-] which now includes a space, period and hyphen. The backslash tells the RE engine to treat that hyphen literally unlike the one in "a-z".
Details about writing a regex here:http://docs.python.org/3/howto/regex.html#regex-howto
Details about using the Re module in Python here: http://docs.python.org/3/library/re.html#module-re
import re
def CheckInput():
city = input('Enter name of city: ')
if re.search(r'\d', city):
raise Exception('Invalid input')
You wouldn't be type checking because in Python 3 all text inputs are strings. This checks for a decimal value in the input using regular expressions and raises an exception if one is found.
val = input("Enter name of city:")
try:
int( val )
except ValueError:
return val
else:
print("No numbers please")
Edit: I saw mention that no number should be present in the input at all. This version checks for numbers at any place in the input:
import re
val = input("Enter name of city:")
if re.search( r'\d', val ) is not None:
print("No numbers please")
else:
return val
You can use the type(variable_name) function to retrieve the type.

Categories