In a function in Django, the user can send me a number or a string, and I want to know if I received a number or a String (Tip: The number will always be an integer between 1-6)
I want to know if it's possible to detect this and how (with an example), as the number or string I'm getting will tell me what to do next.
You can try to convert the string to a number using int(), catching the exception:
def isNum(data):
try:
int(data)
return True
except ValueError:
return False
This returns True only if the string can be converted to an integer number.
What about: if isinstance(data, int):
I'm assuming your number will still be encased in a string, ie. "1" or "4" or "6" - if that's the case, then there are several ways to do it; you could use a regex to check whether it is a number or not, or you could knock up a function that would look something like this
def isNumber(your_input_string):
return len(your_input_string) == 1 and your_input_string in "123456"
Since the number will always be between 1 and 6, it can only be a string of length 1, and it must be contained in the string '123456', since... well, those are the allowed numbers.
EDIT:
As pointed by Martijn Pieters in the comments below, that is a roundabout way of doing it; an easier solution would be just to check whether the string is between '1' or '6'.
def isNumber(your_input_string):
return len(your_input_string) == 1 and '1' <= your_input_string <= '6'
Related
I'm attempting to differentiate between a discord message that is a number and one that is letters in a Pick a Number game for a discord bot. I figured I could just use the startswith parameter to see if the message contained numbers, but it returns a "TypeError: slice indices must be integers or None or have an index method" Whenever I try it. How can I fix this?
if current_guess.startswith('1','2','3'):
current_guess = int(current_guess)
if best_id == "N/A":
best_guess = current_guess
best_id = current_id
else:
if abs(current_guess-number)<abs(best_guess-number):
best_guess = current_guess
best_id = current_id
else:
return
since startswith only allows 3 parameters to search for, I just copied this code 3 times, each checking for three of the numbers 1-9.
I was expecting it to be able to detect whether or not a message consisted of numbers, but it just outputs an error I don't understand.
line 57, in PAN
if current_guess.startswith('1','2','3'):
TypeError: slice indices must be integers or None or have an __index__ method
If I understand your question correctly, you want to check if the message is a number. You can use a try / except:
try:
current_guess = int(current_guess)
except ValueError:
# warn user about only being possible to send digits
startswith accepts only one string to search for; you could write your condition as:
if any(guess.startswith(n) for n in ('1', '2', '3'))):
....
if you just want to know if the first character of a string is a number you could also use isdigit (although that would also match '0'):
if guess[0].isdigit():
...
depending on what you really want to look for you might also consider the re module:
if re.match('^[1-9]', guess)):
...
where ^ means the geginning of the string and [1-9] will match one of the characters in the range from '1' to '9'.
Writing a program:
Input string from the user
print out whether this string is a palindrome or not
Also, I found a few other codes online but want to work with this code only.m Please let me know the error
i = str(input())
for item in i:
print(item)
if int(i[item]) == int(i[-item]):
print('yes')
else:
print('no')
Use a String slice (The i[::-1] will reverse the string):
i = input()
if i == i[::-1]:
print("Yes")
else:
print("No")
This will take the input from the user and compare it against the same input in reverse.
try this:
word="TOT"
i=word[::-1]
if i==word:
print("palandrom")
Although for item in i: loops through every character in the string, there are several problems with your code line if int(i[item]) == int(i[-item]):. First of all, item is going to be a character from your string. So if the user types "hello", then i[item] first looks for i['h']. Since 'h' is a character and not a number, this makes Python think that i is a dictionary and not a string, and thus tells Python to look for a dictionary named i and return the value where the key is h. That won't work since i is your original string, not a dictionary.
It looks like what you meant to do here is compare i[0] (the first character in the string) to i[-1] (the last character in the string), then i[1] to i[-2], and so on. But even you if looped through the position numbers, i[-item] doesn't mathematically give you what you want.
Yet another issue here is that you're checking each character one at a time and returning "yes" or "no". What you ultimately want though is to output one simple answer: whether your string is a palindrome or not.
Also, there's no need to put str() around input(), since input returns a string anyway, even if the user enters only numerals. By the way, even though you're using i as your string variable, the usual convention in programming is to use i to denote some sort of integer, such as one you're iterating through in a for loop. But that's OK for now.
As some of the other answers have shown, i[::-1] is a quick way to return the reverse of a string itself. So if you're OK with seeing the output return True if the string is a palindrome and False if it isn't, then here's an extremely simple way to do it:
i = input()
print(i == i[::-1])
If the string i is identical to itself reversed, then i == i[::-1] returns True. If not, it returns False. The print statement then prints whichever the answer is.
However, if you really do want to do it the long way, testing character by character in a loop, then here's one way to do it. You could make a function that takes in a string and does the work:
def is_palindrome(mystring):
# The "//2" here divides by 2 and ignores the remainder. So if
# there are an even number of letters, we'll test each pair. If
# It's an odd number, then we don't care about the middle character
# anyway. Compare [0] to [-1], then [1] to [-2], [2] to [-3], and so on.
for position in range(0, len(mystring)//2):
# If we've found a mismatched pair of letters, then we can
# stop looking; we know it's not a palindrome.
if mystring[position] != mystring[(-1 * position) - 1]:
print("This is NOT a palindrome")
return # This breaks you out of the entire function.
# If we've gotten this far, then the word must be a palindrome.
print("This is a palindrome")
# Here's where we run the command to input the string, and run the function
mystring = input("Enter your string: ")
is_palindrome(mystring)
The question on my assignment is as follows:
Write a function that takes, as an argument, a string, identified by the variable aString. If the string only contains digits 0 and 1, return the string formed by concatenating the argument with the string "is a binary string." Otherwise, return a string indicating the length of the argument, as specified in the examples that follow. Name this function AmIBinary(aString).
I am having trouble figuring out how to form a loop which searches through a string and determines whether or not the string is a binary string. I understand how to get the length of a string, I just don't understand how to figure out if it is a binary string.
Try this !
import re
def AmIBinary(aString):
#test_str='Vijay'
if re.match("[01]+",aString):
print('Binary string')
else:
print(len(test_str))
#AmIBinary("Vijay")
AmIBinary('010101')
You can use a for loop through a string the same way you can use with a list of numbers.
For example:
numbers = [1, 2, 3, 4]
You can use:
for number in numbers:
# Do something
In your case, you just need to switch the number list by the string you receive as an argument like this:
aString = '100100100'
for number in aString:
# Check if there's a different number than '0' and '1'
Look that in this case you need to compare it with the string version of the number, because you're iterating a string, so each value you receive from the for loop will be a string too.
In the end, you'll probably have something like this:
def AmIBinary(aString):
for number in aString:
if number != '0' and number != '1':
return len(aString)
aString += 'is a binary string'
return aString
As you can see I am iterating through the string to check if any element of it is different than '1' and '0', if it is, I just return the length of the string, otherwise, if I checked every value in the string and everything is fine, I concatenate 'is a binary string' to the original string and return it.
I hope this helps.
Try the build-in function remix without use loop.
def AmIBin(s):
try:
if s.startswith('0b'):
int(s, 2)
else:
int('0b{}'.format(s), 2)
except:
return False
else:
return True
A binary string has been defined as a string that only contains "0" or "1". So, how about checking each 'character' in the string, and if it's not a "0" or "1" you will know that the string is not a binary string.
This is the code I am using to detect if a string contains letters. If none are detected, it allows the program to convert the string to a float. The idea was that I could stop the program from crashing after attempting to convert a string with letters to a float.
for i in range(1, len(argument)):
if argument[i].isalpha():
return False
print("Ran option 1")
else:
return True
print("Ran option 2")
The print lines are just to help me see which part is being executed. As it turns out, neither of them are.
http://puu.sh/ivVI7/8598b82fe8.png
This is a screenshot of the output. In the first half, it detects the "aa" string and does not crash the code. However, in the second half, it fails to detect the single "a" and attempts to convert it to a float, crashing the program. If anybody could lend a hand, it would be greatly appreciated.
If it helps, the rest of the code is here: http://pastebin.com/Cx7HbM4c
You have the print lines after the return command, so they will never be executed. Move the print above the return.
You can also make your code more pythonic and more readable:
for char in argument:
return char.isalpha()
Python strings are 0-based. The test never checks the first character in the string.
for i in range(0, len(argument)):
Filing that knowledge away, the python way (for char in argument) as shown in answers from #DeepSpace and #helmbert seems cleaner.
In Python, arrays are zero-indexed. This means, you need to start iterating at 0, not at 1!
You can reproduce this easily by simply adding a print(argument[i]) into your loop body:
def func(argument):
for i in range(1, len(argument)):
print(argument[i])
func("a") # Prints nothing
func("ab") # Prints "b"
Keeping as closely as possible to your original code, simply start iterating at 0 instead of 1:
for i in range(0, len(argument):
# ...
Easier yet, you can also iterate a string directly:
for character in argument:
print(character) # Will print every single character
# ...
Ok, if you try to find out can you convert string or not, why don't you use function like this:
def convertable(value):
try:
float(value)
return True
except ValueError:
return False
if all you want is to prevent your program from crashing, exceptions are your friends:
argument = "abc"
try:
value = float(argument)
except ValueError as e:
print e, "is unacceptable"
else:
print value, "is acceptable as a float"
finally:
print "alright"
outputs:
could not convert string to float: abc is unacceptable
alright
whereas, if argument = "3.14"
it outputs:
3.14 is acceptable as a float
alright
Of course, you can put all that logic into a function, in case you need to do it many times across your program.
Have fun!
I want to define a recursive function that passes a str and returns a bool telling whether or not the characters in the parameter are in alphabetical order.
Like if I defined said sortfunc('abcdefg') it would return True; and sortfunc('banana') would return False.
How would I approach this? This is what I have so far... but I'm sort of stuck. I understand the concept of recursion but I don't know how to implement it.
def sortfunc(s):
if s == '':
return False
else:
return True if s[0] < s[1:] else False
Here's one possible method:
def is_sorted(s):
if len(s) == 1:
return True # Base case
elif s[0] <= s[1]:
return is_sorted(s[1:]) # Recursive case
else:
return False # Base case
Explanation:
So, whenever, we want to write a recursive function, we always need to think about the following:
How can I break the problem down into smaller steps?
What is the base case? (when I can stop the recursion?)
What is the recursive case? (when do I need to keep going?)
To me, the first step is always the trickiest one -- breaking the problem down. Usually, once we figure out this step, the rest falls into place.
There are usually many different ways to break a problem down, and to a certain extent, which one you pick is a bit arbitrary. In this case, I chose to break the problem down by repeatedly comparing the first two characters in the string.
If the two characters are in order, then I repeat the process, except I remove the first character. If I have only one character left in my string, or if the first two characters are out of order, I know that I can stop and return True or False respectively.
For example, if we visualize calling is_sorted('abcd'), it would look something like this:
call is_sorted('abcd')
'a' is less then 'b'
call is_sorted('bcd')
'b' is less then 'c'
call is_sorted('cd')
'c' is less then 'd'
call is_sorted('d')
only one character left, return True
return True
return True
return True
In contrast, if we tried calling is_sorted('azbc'), it would look something like this:
call is_sorted('azbc')
'a' is less then 'z'
call is_sorted('zbc')
'z' is NOT less than 'b', return False
return False
So then, here are the answers to the three steps:
How can I break the problem down into smaller steps?
Keep comparing the first two characters
What is the base case? (when I can stop the recursion?)
Either when the two characters are out of order, or if I have only one character left
What is the recursive case? (when do I need to keep going?)
If I have two or more characters left in my string.
Notice that the recursive case always requires a "leap of faith" -- you have to trust that calling the is_sorted method will accurately tell you if the rest of the string (besides the first two characters) is correctly sorted or not. It's a bit of an odd feeling -- it feels like we never explicitly told the code how to determine if the string is coded or not, or passed in any information, but it does so anyways!
However, that's part of the beauty of recursion: so long as we correctly define the base case(s) and recursive case(s), it'll magically work.
In your attempt you are missing the recursion part. Please check the following implementation.
def sortfunc(current_string, previous_character = ""):
if current_string == "":
return True # Base condition
if previous_character and previous_character > current_string[0]:
return False # Failure case
return sortfunc(current_string[1:], current_string[0]) # Recursion
If you want to know how to do this without recursion,
def sortfunc(current_string):
return "".join(sorted(current_string)) == current_string
Sample runs:
print sortfunc('abcdefg') # True
print sortfunc('banana') # False
Without less programming logic!
-> Split the string to an array and send this array to function
-> we can easily compare values by converting them to respective ascii values
sortfunc(str) {
for(int i=0;i<str.length;i++){
if ( (int) str[i] >(int) str[i+1] ) {
result = true
}
else
result = false;
return result;
}