lettura simple

Python's isdecimal() Method

Have you ever wondered about Python's isdecimal() method? Well, it's a handy tool that checks if a string consists solely of decimal digits. Here's how you use it:

string.isdecimal()

Even though it takes no parameters, you can't forget those parentheses – they're still a must-have!

This method is a friend of the String objects and is always ready to help you out.

The isdecimal() method is like a trusty sidekick, always letting you know the truth. If your string is made up entirely of decimal digits, it'll return True. But if there's something else hiding in there, you'll get a False.

Note. But keep in mind, this method is a bit of a purist. It only recognizes the characters "0" to "9" as valid decimal digits. It turns a blind eye to punctuation, math symbols like commas or decimal points, and even plus or minus signs in front of numbers.

Let's jump into a quick example.

Say you've got a string assigned to a variable, let's call it "myVar".

>>> myVar = "12345"

Next, you just type myVar.isdecimal() to see if your string is made up of decimal digits only.

>>> myVar.isdecimal()

In this case, you'll get a big thumbs up with a return of True because the string is all numbers.

True

How about we mix things up a bit?

Now assign an alphanumeric string - a mix of numbers and letters - to the variable.

>>> myVar = "12345abc"

Then, let's call upon the isdecimal() method again to check our string.

>>> myVar.isdecimal()

This time, you'll get a False, because our string decided to party with some letters.

False

The isdecimal method keeps its eyes on the prize, only recognizing decimal digits, specifically characters from "0" to "9".

However, remember it's not all-seeing. It may not recognize all numbers because it doesn't see the decimal point ".". It also turns a blind eye to the comma ",", plus "+" or minus "-".

Let's look at this in action. Define a variable, like this:

>>> string = "123.45"

This string is the alphanumeric version of a decimal number "123.45"

Now, test it with the isdecimal() method

>>> string.isdecimal()

This time, you'll find yourself with a False, because our string "123.45" has a decimal point.

False

Just the same, you'll get a False for strings like "+12345", "-12345" or "123,456".

Basically, if there's even a hint of a special or alphabetic character in the string, isdecimal() won't hesitate to give you a False.




Report a mistake or post a question




FacebookTwitterLinkedinLinkedin