Python 3 – String isdecimal() Method
The isdecimal()
method is used in Python 3 strings to determine whether a string is a decimal or not. It returns True
if all characters in the string are decimal and False
if not.
Syntax:
string.isdecimal()
Here, ‘string
‘ is the string that is to be checked for its decimal status.
Let’s look at an example:
string = "12345"
print(string.isdecimal())
In this example, since all characters in the string string
are decimal numbers, the output will be True
.
Now, let’s look at another example:
string = "12.34"
print(string.isdecimal())
In this example, since the string string
contains a decimal point, the output will be False
.
The isdecimal()
method can also be used in conjunction with the isdigit()
method.
Let’s look at an example:
string = "12345"
print(string.isdigit())
print(string.isdecimal())
In this example, both isdigit()
and isdecimal()
methods have the same output since there are no non-digit characters in string
. The output will be True
for both methods.
Now, let’s look at another example:
string = "12345\u00B2"
print(string.isdigit())
print(string.isdecimal())
In this example, the string string
contains a superscript 2 character which is not a digit character. The isdigit()
method will still return True
since superscripts are considered to be digits. However, the isdecimal()
method will return False
since the superscript 2 is not a decimal character.
In summary, the isdecimal()
method can be useful in determining whether a string is comprised of only decimal characters or not.
Here is a code snippet that shows how to use the isdecimal()
method:
string = "12345"
if string.isdecimal():
print("String is decimal")
else:
print("String is not decimal")
This code snippet checks whether the string string
is decimal or not using the isdecimal()
method. If the string is decimal, it will print “String is decimal”. If not, it will print “String is not decimal”.
Conclusion
In conclusion, the isdecimal()
method is useful in Python 3 strings to determine whether a string is a decimal or not. It can be used in conjunction with other string methods to achieve more complex functionality.