Python phone number string validation - python

I'm having some issues that I really would like some help on. Right now I'm trying to get the user to input a phone that only accepts the first three things typed in as numbers. The rest can be letters that will get converted into numbers, but even if the first three things are numbers or letters it will keep repeating. The input has to be in this format (XXX-XXX-XXXX).
examples: (234-SDF-SDFL) this would pass, if (SDF-FSD-UEIE) then the program would ask again until the first three are number. Please and thank you.
phNumber=input("Number: ")
num=phNumber.split("-")
area=num[0]
while area.isdigit() == False :
phNumber=input("Number: ")
num=phNumber.split("-")
area=num[0]

Why dont you use regular expressions? (BTW: Do not use this odd naming, use pythons naming convention: snake case)
import re
phone_number=input("Number: ")
while not re.match(r'^\d{3}-[A-Z]{3}-[A-Z]{4}$', phone_number):
phone_number=input("Number: ")

Related

Why does my /n code not work when I have typed it correctly?

I am trying to run this python code:
print("Welcome to the PyPassword Generator!")
letters = ["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","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"]
symbols = ["!","#","#","$","%","&","*","(",")","/","+"]
numbers = ["1","2","3","4","5","6","7","8","9","0"]
amount_letters = int(input(f"How many letters would you like?/n"))
amount_symbols = int(input(f"How many symbols would you like?/n"))
amount_numbers = int(input(f"How many numbers would you like?/n"))
However, it doesn't meet my satisfaction as I want the user's input on the next line but the /n code doesn't work.
Welcome to the PyPassword Generator!
How many letters would you like?/n (This is where the user input goes)
(But I want it to go here.)
How many symbols would you like?/n (This is where the user input goes)
(But I want it to go here.)
How many numbers would you like?/n (This is where the user input goes)
(But I want it to go here.)
Help would be really appreciated.
You're mixing up \n and /n.
\n gives you a newline.
/n only prints just that - '/n'.

How to Format User Inputs Into Variables in Python

I'm trying to format a user input into variables. I'm a novice to most advanced functions in python, but here's an example prompt:
userInput = input("Enter your four-character list:")
The user is supposed to enter three or four characters, a mix of letters and numbers. I would like to slice up the input into variables that can be plugged into other functions. For example, if the user input is "4 5 s t," I would like each of the four characters to be a variable. Spacing also shouldn't matter, whether it's at least one or five between each.
You can use the split method of strings in python
my_args = userInput.split()
This will return a python list of the input elements regardless of how many spaces there are.
Then you can work with your list like this
for arg in my_args:
#do something

Python - Get a number from a string containing letters, numbers and symbols

I want to get a number from a string, the parts of the number are separated with commas and there are some other symbols too, the number ranges from 1 to 100 million so the number of commas will vary. here's an example:
Input
Balance added **⏣ 5,358**: 127%\n**User Balance**: ⏣ 9,951,203'}
Output:
9951203
I need the number after **User Balance**:, ignoring all numbers before it.
I've tried making a regex myself but i cant seem to get the number after **User Balance**: without also including the words in the string, plus i cant figure out how to deal with the commas, its disheartening to me that ive spent hours on this yet others could do it in a minute, so here i am intending to ask those others :D
Hope i've provided enough information to help you to help me and thanks in advance!
import re
log = "Balance added **⏣ 5,358**: 127%\n**User Balance**: ⏣ 9,951,203'}"
user_balance = re.search(r"User Balance.*?([\d,]+)", log).group(1).replace(",", "")
I don't think I understand wheter the string information change, so this might be a wrong answer. But I always like to use .split or slicing in general in such problems. Like:
my_string = "Balance added **⏣ 5,358**: 127%\n**User Balance**: ⏣ 9,951,203'}"
my_string.split("User Balance**: ⏣")[-1]
This would get you
9,951,203'}
Then, like lucians wrote in his comment, you could try to find integers with try/except or else and combine then.
int(string.split("User Balance**: ⏣")[1].replace("\'}","").replace(",",""))
Output
9951203

Small == Equal while creating simple python code

I'm completely new to Python so all of this is a bit new for me.
I'm trying to create a script in which it by itself thinks of a number and after wards wants the user to guess a number and enter it. It seemed to work but there are wo problems here.
It understands everything however it does not understand the == part.
Because even though the both numbers are the same, it still goes on towards the else statement.
import random
while True:
Thethinker = random.randint(1,10)
Guessnumber = (input("Guess a random number "))
if Guessnumber == Thethinker:
print("Correct")
print(Thethinker)
else:
print("Not correct")
print(Thethinker)
Any help?
Assuming Python 3, input returns a string.
In Python, a string and a number can never be "equal"; you have to transform one or the other. E.g, if you use
Thethinker = str(random.randint(1,10))
then the equality-comparison with another string can succeed.
Your input returns a string instead of an integer. To get an integer do:
int(Guessnumber)
This is better than using str() because then if you ever want to change the numbers, you wouldn't be able to do that without doing the method I suggested
As far as I know, I don't do much Python

Is there a way other than 'try...except' and '.isdigit()' to check user input in Python 2?

I am currently trying to learn Python 2.7 via Learn Python The Hard Way, but have a question about Study Drill 5 of Exercise 35.
The code I'm looking at is:
choice = raw_input("> ")
if "0" in choice or "1" in choice:
how_much = int(choice)
else:
dead("Man, learn to type a number.")
The study drill asks if there is a better way than checking if the number contains zero or one, and to look at how int() works for clues.
I obviously want to be able to accept any number given by the user while dismissing strings, and I understand that int() converts what was given in raw_input() into a number.
So, I tried a couple of ways of amending the if statement which threw up fatal errors when typing a string, but struggled to find anything suitable. I tried variations of the following code, and now understand why they don't work:
choice = int(raw_input("> "))
if choice > 0:
After searching SO I discovered this answer which gives two ways to solve the problem, however try...except and .isdigit() aren't something mentioned in the book at this point.
Is there any other ways to achieve taking user input, converting it to an integer if necessary, and returning an error if not that is appropriate for this stage of the book?
You can write your own is_digit function
def my_digit(input):
digits = ['0','1','2','3','4','5','6','7','8','9']
for i in list(input):
if not i in digits:
return False
return True
So, firstly read what jonrsharpe linked to in the comments and accept that try-except is the best way of doing this.
Then consider what it means to be an integer:
Everything must be a digit (no decimal point, too)
So that's what you check for. You want everything to be a digit.
Thus, for a represents_integer(string) function:
for every letter in the string:
check that it is one of "0", "1", "2", ..., "9"
if it is not, this is not a number, so return false
if we are here, everything was satisfied, so return true
Note that the check that is is one of might require another loop, although there are faster ways.
Finally, consider "", which won't work in this method (or GregS').
Since you already learned sets, you can test that every character is a digit by something like
choice = choice.strip()
for d in choice:
if d not in "0123456789":
# harass user for their idiocy
how_much = int (choice)

Categories

Resources