Detect leading white space - Python - python

I would like to know if the user entered a space before the number. Currently if you push space and then enter a number the program ignores the space and sees it as you just entered a number.
I tried a few methods found on this site but I must be missing something.
import re
while True:
enternum=input('Enter numbers only')
try:
enternum=int(enternum)
except ValueError:
print ('Try again')
continue
conv = str(enternum) # converted it so I can use some of the methods below
if conv[0].isspace(): # I tried this it does not work
print("leading space not allowed")
for ind, val in enumerate(conv):
if (val.isspace()) == True: # I tried this it does not work
print('leading space not allowed')
if re.match(r"\s", conv): # I tried this it does not work (notice you must import re to try this)
print('leading space not allowed')
print('Total items entered', len(conv)) # this does not even recognize the leading space
print ('valid entry')
continue

The problem in your example code is that you convert enternum to an integer (thus removing the spaces) before checking for spaces. If you just check enternum[0].isspace() before converting it to an integer, it will detect the space.
Don't forget to check that the user entered something instead of just pressing enter, otherwise you'll get an IndexError when trying to access enternum[0].
while True:
enternum = input('Enter numbers only')
if not enternum:
print('Must enter number')
continue
if enternum[0].isspace():
print('leading space not allowed')
continue
enternum = int(enternum)
...
You didn't specify why you want to prohibit spaces specifically, so you should consider if that's what you actually want to do. Another option is using enternum.isdecimal() (again, before converting to int) to check if the string only contains decimal digits.

Related

How do I make an input() detect if the user input is something other than a string?

I am fairly new to Python and I wanted to generate a simple user input that asks for your name. I got the prompt to work but when I added code that detects if the input is not a string, it doesn't let me input anything at all.
It was working up until I added the code that tells the user if they used an unsupported character.
Here's the code I have so far:
while True:
name = input('What is your name? ')
if name is str:
print('Hi,%s. ' % name)
if name != str:
print('That is not a valid character!')
Python supplies methods to check if a string contains on alphabets, alphanumeric or numeric.
isalpha() returns True for strings with only alphabets.
isalnum() returns True for strings with only alphabets and numbers and nothing else.
isdigit() returns True for strings with only numbers.
Also your if-else statement is off
name = input('What is your name? ')
if name.isalpha():
print('Hi,%s. ' % name)
else:
print('That is not a valid character!')
When you do
name = input('What is your name? ')
you get a string called name, so checking it it is a string won't work.
What you can check is if it's an alphabetical character, using isalpha:
if name.isalpha():
# as you were
There are various other string methods ( see here ) which start is to check for numbers, lower case, spaces and so on.

How to make a string that only includes spaces be an invalid input in python

I'm a newbie in coding using python and I'm trying to write a piece of small code that prints whatever you input in the terminal, but I don't want anything that only includes spaces and no other characters or doesn't even have an input to be printed. Here's the code:
while True:
my_name= input("> ")
if "" in my_name:
print("I don't know what that means. Please choose a valid answer.")
else:
print(f"Ah, I see, so your name is {my_name}?")
would love to have multiple solutions to this, and thank you if you helped :)
https://docs.python.org/2/library/stdtypes.html#str.isspace
I think this should do the trick
if my_name.isspace():
print("Your name is full of spaces")
Python isspace() method is used to check space in the string. It returns true if there are only white space characters in the string. Otherwise it returns false.
ex:
# Python isspace() method example
# Variable declaration
str = " " # empty string
# Calling function
str2 = str.isspace()
# Displaying result
print(str2)
There's one way of doing that by using exceptional handling for no input using try - except block and a flag variable that checks if input doesn't contain only spaces.
try:
flag = False
my_name = input()
for i in my_name:
if i != ' ':
flag = True
if flag:
print(my_name)
else:
print('Invalid input')
except:
print('No input')
The other ways can be using the built in function strip() which removes the trailing and leading spaces in input.
If the input has only spaces then strip() will remove all of them resulting in an empty string.
try:
my_name = input()
if my_name.strip() == '':
print('Invalid input')
else:
print(my_name)
except:
print('No input')
Like this, you can use bools:
while True:
my_name= input("> ")
if my_name.strip():
print(f"Ah, I see, so your name is {my_name}?")
else:
print("I don't know what that means. Please choose a valid answer.")

How do i get my script to nicely reject invalid characters

at the moment if you put a character instead of a number in the input it gives an ugly error. I would like the script to output something like "Invalid character! Please enter a digit." whats something i can do to fix this?
import random
import string
string.ascii_letters='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
string.number_symbols='!##$%^&*()'
userLetterInput = int(input("How many letters would you like in your password?: "))
userSymbolInput = int(input("How many symbols would you like in your password?: "))
letterResult = ''.join([random.choice(string.ascii_letters) for i in range(userLetterInput)])
symbolResult = ''.join([random.choice(string.number_symbols) for i in range(userSymbolInput)])
print("".join(letterResult + symbolResult))
You can use a try/except statement in a loop to catch the exception and display a message for the user. The try/except statement catches the exception thrown when the user enters alphabetic characters, whereas the loop repeats the query for a number until the user gives a valid input.
import random
import string
string.ascii_letters='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
string.number_symbols='!##$%^&*()'
while True: # Repeat the question until valid input is given
try: # Catch ValueError which gets thrown when letters are entered
userLetterInput = int(input("How many letters would you like in your password?: "))
break # Exit the loop if no exception is thrown
except ValueError:
print("Invalid character! Please enter a digit.")
while True:
try:
userSymbolInput = int(input("How many symbols would you like in your password?: "))
break
except ValueError:
print("Invalid character! Please enter a digit.")
letterResult = ''.join([random.choice(string.ascii_letters) for i in range(userLetterInput)])
symbolResult = ''.join([random.choice(string.number_symbols) for i in range(userSymbolInput)])
print("".join(letterResult + symbolResult))
Instead of using a while True loop, you could of course also declare a boolean (e.g. invalid_input) which is True at first and gets set to False after the user entered a valid number.
you can check input type with "isinstance":
isinstance(1, int)
isinstance('be', str)

raw_input check to allow for reinitiation of same function

I was banging my head against my desk on this one, because I'm an idiot, and I've finally gotten it to work. This is a simplified, dumb version of my actual code (which is why the function's purpose seems so inane) but I'm curious whether there is (or rather, am sure there must be) a more efficient way of doing the following:
def get_char():
character = raw_input("Enter the character you would like to use.\n >")
if character.isalpha:
proceed = raw_input("The value entered is " + character + "\nWould you like to proceed?(Y/N)\n>")
while True:
if proceed in "N,n":
raw_input("Press enter to try again with another value.")
character = get_char()
break
else:
break
return character
#print character
character = get_char()
print character
What I want to end up with is a way of checking that the user's input is what they intended. Until I set character = get_char() in the while loop, I was getting problematic output (i.e. incorrect final values for character); having fixed that, I've noticed that if I include the print statement at the end of the get_char() definition, it prints out the number of times a "no" choice has been made +1. While the end result is still fine, I'm curious whether the fact that it seems to be holding iterations in a queue, as indicated by the multiple prints upon inclusion of the print statement, means that there's a better way of doing this. Thanks in advance for any help!
UPDATE:
Just in case anyone else needs help with this same issue, based on the suggestion by millerdev, I've adjusted the code to the following, which works just the same except without the self-call which was generating unnecessary character queuing:
def get_char():
while True:
character = raw_input("Enter the character you would like to use\n >")
if character.isalpha:
proceed = raw_input("The value entered is " + character + "\nWould you like to proceed? (Y/N)\n>")
if proceed in ("N", "n"):
raw_input("Press enter to try again with another value.")
else:
break
#print character
return character
character = get_char()
Because of character = get_char(), your loop only runs once, because it will recurse deeper if it fails instead of iterating again. This probably isn't what you want, because it's slower and runs the risk of overflowing the stack. The cleanest way to do this would probably be (you could replace my messages with yours easily):
def get_char(is_valid = lambda c: True):
while True:
c = raw_input('enter a character > ')
if is_valid(c):
keep = raw_input('do you want to use {0}? (Y/N)> '.format(c)).lower()
if 'n' in keep:
continue # go back to While True line
return c
print('{0} is not a valid character'.format(c))
Session:
>>> get_char()
enter a character > a
do you want to use a? (Y/N)> n
enter a character > c
do you want to use c? (Y/N)> no
enter a character > x
do you want to use x? (Y/N)> y
'x'
At least, this is the cleanest in my opinion. Your implementation has a few other problems, like proceed in "N,n", which would also count comma as an n, and if the character isn't isalpha, you still return it.
Is this what you're aiming for?
def get_char():
while True:
character = raw_input("Enter the character you would like to use.\n >")
if character.isalpha: # this is always true; add parens if that's what you want, otherwise remove it
proceed = raw_input("The value entered is " + character + "\nWould you like to proceed? (Y/n)\n>")
if proceed.lower() == "n":
raw_input("Press enter to try again with another value.")
character = get_char()
return character
character = get_char()
print character

List from string of digits

I'm getting a string from input() which consists of digits separated by spaces (1 5 6 3). First I'm trying to check that the input only consists of digits with the isdigit() function but because of the spaces I can't get it to work. Then I convert the string to a list using the split() function.
What I need is to make a list from input and make sure it only consists of digits, else send a message and ask for a new input. Is it maybe possible to add a parameter to isdigit() that makes an exception for spaces?
What you're describing is a look before you leap approach, i.e. checking first whether the input is conforming, and then parsing it. It's more pythonic to use a Easier to ask for forgiveness than permission approach, i.e. just do it and handle exceptions:
s = raw_input() # input() in Python 3
try:
numbers = map(int, s.split())
except ValueError:
print('Invalid format')
Probably a lot more complicated than it needs to be but this will return true if the string consists of only digits:
not sum([not i.isdigit() for i in thestring.split()])
You should try converting and, upon exception ask again. This is how I'd do it. (I've included a Ctrl+c escape to avoid being locked in the loop.
import sys
list = None
while True:
try:
print "Enter your digits : ",
content = raw_input()
list = [int(x) for x in content.strip().split(" ")]
break
except KeyboardInterrupt: # Presses Ctrl+C
print "Exiting due to keyboard interrupt"
sys.exit(-1)
except:
print "Bad content, only digits separated by spaces"
print list

Categories

Resources