List from string of digits - python

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

Related

How to remove all non-numeric characters (except operators) from a string in Python?

I would like to remove all non-numeric characters from a string, except operators such as +,-,*,/, and then later evaluate it. For example, suppose the input is 'What is 2+2?' The result should be '2+2' - keeping only the operator symbols and numeric digits.
How can I do this in Python? I tried this so far, but can it be improved?
def evaluate(splitted_cm):
try:
splitted_cm = splitted_cm.replace('x', '*').replace('?', '')
digs = [x.isdigit() for x in splitted_cm]
t = [i for i, x in enumerate(digs) if x]
answer = eval(splitted_cm[t[0]:t[-1] + 1])
return str(answer)
except Exception as err:
print(err)
You can use regex and re.sub() to make substitutions.
For example:
expression = re.sub("[^\d+-/÷%\*]*", "", text)
will eliminate everything that is not a number or any of +-/÷%*. Obviously, is up to you to make a comprehensive list of the operators you want to keep.
That said, I'm going to paste here #KarlKnechtel's comment, literally:
Do not use eval() for anything that could possibly receive input from outside the program in any form. It is a critical security risk that allows the creator of that input to execute arbitrary code on your computer.

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.")

Detect leading white space - 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.

linear search in python programming

I have wriiten a code for linear search in python language. The code is working fine for single digit numbers but its not working for double digit numbers or for numbers more than that. Here is my code.
def linear_search(x,sort_lst):
i = 0
c= 0
for i in range(len(sort_lst)):
if sort_lst[i] == x :
c= c+1
if (c > 0):
print ("item found")
else :
print ("not found")
sort_lst= input("enter an array of numbers:")
item= input("enter the number to searched :")
linear_search(item,sort_lst)
any suggestions ?
Replace
sort_lst= input("enter an array of numbers:")
with:
print 'enter an array of numbers:'
sort_lst= map(int, raw_input().strip().split(' '))
If all you want is a substring search, you can just use this
print("item found" if x in sort_lst else "not found")
If you want to get more complicated, then you need to convert your input from a string to an actual list.
(assuming space separated values)
sort_lst= input("enter an array of numbers:").split()
Then, that's actually a list of strings, not integers, but as long as you compare strings to strings, then your logic should work
Note: the print statement above will still work in both cases
This may be a case of confusion between behavior in python 2.x and python 3.x, as the behavior of the input function has changed. In python 2, input would produce a tuple (12, 34) if you entered 12, 34. However, in python 3, this same function call and input produces "12, 34". Based on the parenthesis in your prints and the problem you're having, it seems clear you're using python 3 :-)
Thus when you iterate using for i in range(len(sort_lst)):, and then looking up the element to match using sort_lst[i], you're actually looking at each character in the string "12, 34" (so "1", then "2", then ",", then " ", etc.).
To get the behavior you're after, you first need to convert the string to an actual list of numbers (and also convert the input you're matching against to a string of numbers).
Assuming you use commas to separate the numbers you enter, you can convert the list using:
sorted_int_list = []
for number_string in sort_list.split(","):
sorted_int_list = int(number_string.strip())
If you are familiar with list comprehensions, this can be shortened to:
sorted_int_list = [int(number_string.strip()) for number_string in sort_list.spit(",")]
You'll also need:
item = int(item.strip())
To convert the thing you're comparing against from string to int.
And I'm assuming you're doing this to learn some programming and not just some python, but once you've applied the above conversions you can in fact check whether item is in sorted_int_list by simply doing:
is_found = item in sorted_int_list
if is_found:
print ("Found it")
else:
print ("Didn't find it :-(")
Notes:
"12, 34".split(",") produces ["12", " 34"], as the split function on strings breaks the string up into a list of strings, breaking between elements using the string you pass into it (in this case, ","). See the docs
" 12 ".strip() trims whitespace from the ends of a string

How do I limit an input in python so it will only allow 0 or 1's?

Ive got a binary converter in python and I want to know how to limit my input to certain numbers only, in this case. Only 1's or 0's. So 101010001 is valid but 44 is not for example. Thanks.
You can also try to attempt to convert it to integer as binary, and print message if that fails.
query = raw_input("enter binary number ")
try:
is_bin = int(query,2)
is_bin = True
print "correct number"
except ValueError:
is_bin = False
print "not a binary number"
You will need to use Regular Expressions. You need to make it match 0 or 1 in any position. The regex in this case is [01]*
You can't prevent the string from being input, but you can match it against a regular expression after the fact and take appropriate action. Raising an exception is one possibility.
import re
if not re.match("^[01]*$", input_value):
raise ValueError("Not a binary number")
Without regular expressions:
if all(ch in "01" for ch in input_str):
raise ValueError("'{}' is not valid binary".format(input_str))
Regular expressions work, but so does simple iteration:
def binaryConverter(input_value):
for c in input_value:
if c not in '01':
# do something here, for example:
raise ValueError("Not a binary number")
return int(input_value, 2)
If you just want a simple binary conversion, you can just use int(input_value, 2) This will automatically raise a ValueError for any characters that aren't 0 or 1.

Categories

Resources