Home > OS >  How to differentiate between a number and a letter or sign?
How to differentiate between a number and a letter or sign?

Time:02-18

If I have a digit within a string I can just do:

x = "2"
x.isdigit()

and I get True. But when I do this:

isinstance(x, str)

By my understanding this also results in True.

My question is now how can I tell if it is a character or a number?

CodePudding user response:

Use isalpha() for this:

x = "2"
x.isalpha()

Returns False

CodePudding user response:

The isdigit number checks every character in string and checks if its a digit or not, in other words, can be an number or not, it returns true if every digit is integer. while the isinstance primarily checks the datatype of the value you pass.

x='2'
isinstance(x,integer)

Since x itself is a string, isinstance(x,str) returns true. So, to find whether a string contains a number or character, just use x.isdigit(), it will always return true if its a digit otherwise false.

  • Related