w3resource

Python: Check whether a given string is number or not using Lambda

Python Lambda: Exercise-9 with Solution

Write a Python program to check whether a given string is a number or not using Lambda.

Sample Solution:

Python Code :

# Define a lambda function 'is_num' that checks if a given string 'q' represents a number:
# It first removes the first decimal point in the string using 'replace()',
# then checks if the resulting string is composed of digits using 'isdigit()'
is_num = lambda q: q.replace('.', '', 1).isdigit()

# Check if the given strings are numeric by using the 'is_num' lambda function and print the results
print(is_num('26587'))
print(is_num('4.2365'))
print(is_num('-12547'))
print(is_num('00'))
print(is_num('A001'))
print(is_num('001'))

# Print a line break to separate the previous output from the next set of results
print("\nPrint checking numbers:")

# Define a lambda function 'is_num1' that further checks if a string represents a number by
# excluding a minus sign at the beginning if present and then using the 'is_num' lambda function
# This function calls 'is_num' on the string without the leading '-' if the string starts with '-'
is_num1 = lambda r: is_num(r[1:]) if r[0] == '-' else is_num(r)

# Check if the given strings (with a possible leading '-') are numeric using 'is_num1' lambda function and print the results
print(is_num1('-16.4'))
print(is_num1('-24587.11')) 

Sample Output:

True
True
False
True
False
True

Print checking numbers:
True
True

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to extract year, month, date and time using Lambda.
Next: Write a Python program to create Fibonacci series upto n using Lambda.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/lambda/python-lambda-exercise-9.php