Is there a string.isnumeric function? [duplicate] - python

This question already has answers here:
Using isdigit for floats?
(8 answers)
Closed 8 years ago.
I am already using string.letters, string.digits and string.hexdigits to validate some of my User Input Fields. However, I have a need to validate a floating point number but cannot seem to find an equivalent call. No decimal point is acceptable as is one, but two or more should flag an Error! Is there function for this or do I need write my own validation routine?
Thank you...

There is one, but it doesn't work for decimal points. You could easily write what you want, however, by catching the ValueError:
def is_numeric_inc_point(s):
try:
float(s)
except ValueError:
return False
return True
Demo:
>>> is_numeric_inc_point('5')
True
>>> is_numeric_inc_point('4.8')
True
>>> is_numeric_inc_point('6..2')
False

Related

How can I tell if a string in python is either an int or float using if condition? [duplicate]

This question already has answers here:
How do I check if a string represents a number (float or int)?
(39 answers)
Closed 7 months ago.
I am getting different strings, some are numbers, for example: "1", "afd76", "dddd", "521129" and "0.1423105". I need to check if they are valid numbers before I can continue. In the above examples all are numbers apart from "afd76" and "dddd".
isdigit and isnumeric wont do because they can only verify if the string is an int, for example:
"3".isdigit() is true but "3.0".isdigit() is false
"3".isnumeric() is true but "3.0".isnumeric() is false
Is there any elegant way to do this check other than force casting and deciding what to do depending on the exception?
You can try casting the string into float:
def is_number(num):
try:
float(num)
return True
except ValueError:
return False
Examples:
>>> is_number('123')
True
>>> is_number('123a')
False
>>> is_number('123.12')
True
>>> is_number('3.0')
True

Python decimal format [duplicate]

This question already has answers here:
How to round values only for display in pandas while retaining original ones in the dataframe?
(1 answer)
Can a variable be used in Python to define decimal places
(3 answers)
Set Decimal Point Precision in a Pandas Dataframe
(2 answers)
Closed 8 months ago.
I've looked around and I cannot find an anwser to my question.
I need decimal formatting where the decimal can be different depending on the situation. For this situation I want to pass a variable containing the decimal value.
The values I'm getting from my pandas DataFrame are in this format 3.18e-06, which in this case needs to be turned into 8 decimals, e.g., 3.18123456
Can I either turn my pd DF into an 8 decimal based float64 or can i somehow convert 3.18e-06 into 8 decimals after grabbing it from my db?
Preferably I want to pass a variable containing the decimal for formatting.
Something like:
decimal = 0.00000001
{0:.{decimal}f}".format(a)
EDIT:
In the end, none of the suggested options did it for me. Maybe I didn't phrase my question well enough. I'll share my solution here for anyone else who might need it.
ticksize is a variable which changes depending on the Binance Trading pair you're using, it comes in a format like: 0.00001 or 0.0000001.
async def get_precision(ticksize):
a = '{:.{prec}f}'.format(ticksize, prec=15)
regex = "..(\d+1).*"
try:
b = re.match(regex, str(a))[1]
precision = len(b)
return precision
except Exception as e:
print(f'An exception has occured on get_precision - {e}')
return False
# this function returns the length of ticksize starting from the first 0 after the dot.
# Now that we have our precision we can use a string format to get what we need.
last_buy = '{:.{prec}f}'.format(a, prec=precision)
#returns: Last purchase price for XRPBTC: 0.00001588
float("8.99284722486562e-02") # 0.0899284722486562
and now with 'rounding'
"{:.8f}".format(float("8.99284722486562e-02")) # '0.08992847'

Converting a string to a numerical value [duplicate]

This question already has answers here:
How to extract a floating number from a string [duplicate]
(7 answers)
Closed 8 years ago.
I wander if there is a simple way to convert a string to a number, knowing that the string begins with numbers but can contain non numerical characters.
For example: my_str = "36.12minuts"
I remember a function in Visual Basic that does the conversion directly :
my_str = "36.12minuts"
val(my_str) => 36.12
How about Python?
def digitsndots(text):
if text in ["1","2","3","4","5","6","7","8","9","0","."]:
return True
else:
return False
num = float(filter(digitsndots, "36.12minuts"))
print num
When using this make sure your string does not have digits in between like "1.a.34.c" (courtesy of #Taha)

checking string is number or not in python [duplicate]

This question already has answers here:
How do I check if a string represents a number (float or int)?
(39 answers)
Closed 9 years ago.
Which of the following is the best way of checking if a string could be represented as number?
a)
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
b)
Import re
check_regexp = re.compile(“^\d*\.?\d*$”)
c)
def isNumber(token):
for char in token:
if not char in string.digits: return false
return True
d)
import re
check_replace = lambda x: x.replace(‘.’,’’,1).isdigit()
All four versions do different things. As the first version is the only one that correctly handles negatives, I would prefer it in almost all cases. Even if the other versions were adjusted to return the same values as the first version, I would prefer the first version for clarity. However, if the input format needs to be more strict than what float accepts, perhaps not allowing inputs like '123e+4', then a correctly-written regex would probably be the simplest solution.
You can this Python code, it will find string is number or float value.
def typeofvalue(text):
try:
int(text)
return 'int'
except ValueError:
pass
try:
float(text)
return 'float'
except ValueError:
pass
return 'str'
typeofvalue("1773171")

How can I check if a string has a numeric value in it in Python? [duplicate]

This question already has answers here:
How do I check if a string represents a number (float or int)?
(39 answers)
Closed 7 months ago.
For example, I want to check a string and if it is not convertible to integer(with int()), how can I detect that?
Use the .isdigit() method:
>>> '123'.isdigit()
True
>>> '1a23'.isdigit()
False
Quoting the documentation:
Return true if all characters in the string are digits and there is at least one character, false otherwise.
For unicode strings or Python 3 strings, you'll need to use a more precise definition and use the unicode.isdecimal() / str.isdecimal() instead; not all Unicode digits are interpretable as decimal numbers. U+00B2 SUPERSCRIPT 2 is a digit, but not a decimal, for example.
You can always try it:
try:
a = int(yourstring)
except ValueError:
print "can't convert"
Note that this method outshines isdigit if you want to know if you can convert a string to a floating point number using float

Categories

Resources