So I have a String called 'Number' with 'abf573'. The task is, to find out if the String 'Number' just has characters and numbers from the Hexadecimal System.
My plan was to make a for loop, where we go through each position of the String 'Numbers', to check with an if statement if it is something out of the Hexadecimal System. To check that, I thought about writing down the A-F, a-f and 0-9 into Lists or separat Strings.
My Problem now is, that I have never done something like this in Python. I know how to make for loops and if-/else-/elif-Statements, but I dunno how to implement this in to this Problem.
Would be nice, if someone can give me a hint, how to do it, or if my way of thinking is even right or not.
I find it quite smart and fast to try to convert this string into an integer using int(), and to handle the exception ValueError which occurs if it is not possible.
Here is the beautiful short code:
my_string = 'abf573'
try:
result = int(my_string, 16)
print("OK")
except ValueError:
print("NOK")
Strings are iterables. So, you can write
Number = '12ab'
for character in Number:
if character in 'abcdef':
print('it is HEX')
Also, there is an isdigit method on strings, so your number is hex is not Number.isdigit()
Related
I am trying to check if my input is a string with try-except block. The function runs without an error. However it checks if the input is an integer, not string. How can I inverse this?
def lexicon(word):
while True:
try:
a=str(input(word))
print("Input is a string. string = ", a)
except ValueError:
print("Oops..Input is not supposed to be a number. Try again!")
return a
b=lexicon("Enter the word you'd like: ")
As discussed with user pavel in the comments to his answer, there are two different styles to code for a problem like this: EAFP ("Easier to Ask for Forgiveness than Permission"), meaning that you make your code work on an assumption and take action if it fails; and LBYL ("Look Before You Leap"), in which you first check whether your assumption is true, and then choose the appropriate action to take.
The try/except route is EAFP, since it just executes the code in the try block without bothering to first check whether it would work. If you want to do it in LYBL style, you would explicitly need to ascertain whether the user input is a string representation of a numeric value, and then act accordingly. I'll provide skeletal code for both approaches below. However, note that Python is a little weird compared to other languages in that it seems to have a certain cultural favour for EAFP.
Also, since you are only asking about checking for integers, I will focus on that here. This means that the code will accept floats as valid inputs.
EAFP: try/except
The problem that presumably trips you up is that input always returns a string, so testing if it is a string is nonsensical and will always yield True. However, note that try/except is only an abrigded version of error handling that you can do in Python; the full version is try/except/else/finally. The else block takes effect if no except blocks are executed, and finally is always run at the end. So you could check whether your input is an integer, and make the program raise a failure if that check succeeds. I admit however that this does seem a bit backwards.
try:
a = int(input())
except ValueError:
# do whatever
else:
raise ValueError("Input must not be an integer")
LBYL: if/else
str objects have several methods to test their contents without having to run into errors. For example, .isalpha() checks if all characters are in the alphabet (which returns False however if you include spaces and special characters); isnumeric() checks whether the string is a representation of a number; etc. See a full list here. So depending on what kind of inputs you want to allow, you would need to use one of these methods, or a combination of them, in an if block. The code below essentially does the same thing as the try/except/else version above, using .isdigit() which returns True if all characters in the string are digits (i.e., the same kind of input for which int(a) would succeed).
Note also that I am making use of the new assignment operator := in this code, which is new to Python 3.8. This way, you don't need to explicitly assign the variable a first, however it's a bit harder to catch where the code actually executes an input() function. If you code for backwards compatibility, or don't like the look of this, you'd have to go with the classical a = input() first.
if (a := input()).isdigit():
raise ValueError("Input must not be an integer")
# do whatever
If you want specifically to check the value type of the string, you're better off using if/else and isinstance:
if not isinstance(word, str):
raise TypeError(f"Expecting a string as a value, not {type(word)}.")
else:
#do something
I created a text file and opened it in Python using:
for word_in_line in open("test.txt"):
To loop through the words in a line in txt file.
The text file only has one line, which is:
int 111 = 3 ;
When I make a list using .split():
print("Input: {}".format(word_in_line))
line_list = word_in_line.split()
It creates:
['int', '111', '=', '3', ';']
And I was looking for a way to check if line_list[1] ('111') is an integer.
But when I try type(line_list[1]), it says that its str because of ''.
My goal is to read through the txt file and see if it is integer or str or other data type, etc.
What you have in your list is a string. So the type coming is correct and expected.
What you are looking to do is check to see if what you have are all digits in your string. So to do that use the isdigit string method:
line_list[1].isdigit()
Depending on what exactly you are trying to validate here, there are cases where all you want are purely digits, where this solution provides exactly that.
There could be other cases where you want to check whether you have some kind of number. For example, 10.5. This is where isdigit will fail. For cases like that, you can take a look at this answer that provides an approach to check whether you have a float
I don't agree with the above answer.
Any string parsing like #idjaw's answer of line_list[1].isdigit() will fail on an odd edge case. For example, what if the number is a float and like .50 and starts with a dot? The above approach won't work. Technically we only care about ints in this example so this won't matter, but in general it is dangerous.
In general if you are trying to check whether a string is a valid number, it is best to just try to convert the string to a number and then handle the error accordingly.
def isNumber(string):
try:
val = int(string)
return True
except ValueError:
return False
I am extracting a string out of a JSON document using python that is being sent by an app in development. This question is similar to some other questions, but I'm having trouble just using x = ast.literal_eval('[0448521958, +61439800915]') due to the plus sign.
I'm trying to get each phone number as a string in a python list x, but I'm just not sure how to do it. I'm getting this error:
raise ValueError('malformed string')
ValueError: malformed string
your problem is not just the +
the first number starts with 0 which is an octal number ... it only supports 0-7 ... but the number ends with 8 (and also has other numbers bigger than 8)
but it turns out your problems dont stop there
you can use regex to fix the plus
fixed_string = re.sub('\+(\d+)','\\1','[0445521757, +61439800915]')
ast.literal_eval(fixed_string)
I dont know what you can do about the octal number problem however
I think the problem is that ast.literal_eval is trying to interpret the phone numbers as numbers instead of strings. Try this:
str = '[0448521958, +61439800915]'
str.strip('[]').split(', ')
Result:
['0448521958', '+61439800915']
Technically that string isn't valid JSON. If you want to ignore the +, you could strip it out of the file or string before you evaluate it. If you want to preserve it, you'll have to enclose the value with quotes.
I'm building a simple email verifier. I need to compare the local-parts current letter to a list of valid characters. So essentially I'm asking how do I check to see if the current letter I'm on in local-part is equivalent to a letter in the ENTIRE list of valid chars. If it is a valid character, local-part will go to the next letter in its string and go through the list of valid characters to see if this too is and so on until it reaches the # symbol unless there isn't a valid character.
I'm fairly new to python so I don't know how nested for loops work.
for ch in local:
for ch in valChar:
if(ch ==ch) <----problem
This is what I currently have written for the loops. Is "ch" a variable or some type of syntax to represent char?
You don't need nested loop in this case, thanks to the in operator:
for c in local:
if c in valChar:
performvalidaction(c)
else:
denoteasinvalid(c)
What identifier to use (c, ch, or anything else) is pretty indifferent, I tend to use single-character identifiers for loop variables, but there's no rule saying that you must.
If you did have to use two nested loops, you'd just use different loop variables for the two loops.
In fact you don't even need one loop here (you could instead work e.g with Python's sets, for example) -- much less two -- but I guess using one loop is OK if it's clearer for you.
Let me explain the for loop for you:
for eachitem in file:
do something
eachitem is a variable of one specific value of a file/dictionairy etc..
ch is a variable, you can replace it with any valid identifier:
for local_ch in local:
for valChar_ch in valChar:
if(local_ch == valChar_ch): <----No problem
You need to validate an email address, i would use a regular expression:
\b[A-Z0-9._%+-]+#[A-Z0-9.-]+.[A-Z]{2,6}\b
This question already has answers here:
How can I check if a string represents an int, without using try/except?
(23 answers)
Closed 9 years ago.
I have an application that has a couple of commands.
When you type a certain command, you have to type in additional info about something/someone.
Now that info has to be strictly an integer or a string, depending on the situation.
However, whatever you type into Python using raw_input() actually is a string, no matter what, so more specifically, how would I shortly and without try...except see if a variable is made of digits or characters?
In my opinion you have two options:
Just try to convert it to an int, but catch the exception:
try:
value = int(value)
except ValueError:
pass # it was a string, not an int.
This is the Ask Forgiveness approach.
Explicitly test if there are only digits in the string:
value.isdigit()
str.isdigit() returns True only if all characters in the string are digits (0-9).
The unicode / Python 3 str type equivalent is unicode.isdecimal() / str.isdecimal(); only Unicode decimals can be converted to integers, as not all digits have an actual integer value (U+00B2 SUPERSCRIPT 2 is a digit, but not a decimal, for example).
This is often called the Ask Permission approach, or Look Before You Leap.
The latter will not detect all valid int() values, as whitespace and + and - are also allowed in int() values. The first form will happily accept ' +10 ' as a number, the latter won't.
If your expect that the user normally will input an integer, use the first form. It is easier (and faster) to ask for forgiveness rather than for permission in that case.
if you want to check what it is:
>>>isinstance(1,str)
False
>>>isinstance('stuff',str)
True
>>>isinstance(1,int)
True
>>>isinstance('stuff',int)
False
if you want to get ints from raw_input
>>>x=raw_input('enter thing:')
enter thing: 3
>>>try: x = int(x)
except: pass
>>>isinstance(x,int)
True
The isdigit method of the str type returns True iff the given string is nothing but one or more digits. If it's not, you know the string should be treated as just a string.
Depending on your definition of shortly, you could use one of the following options:
try: int(your_input); except ValueError: # ...
your_input.isdigit()
use a regex
use parse which is kind of the opposite of format
Don't check. Go ahead and assume that it is the right input, and catch an exception if it isn't.
intresult = None
while intresult is None:
input = raw_input()
try: intresult = int(input)
except ValueError: pass