How do I check if a string is a number (float)?

后端 未结 30 3978
暗喜
暗喜 2020-11-21 05:16

What is the best possible way to check if a string can be represented as a number in Python?

The function I currently have right now is:

def is_numb         


        
30条回答
  •  一个人的身影
    2020-11-21 05:41

    I know this is particularly old but I would add an answer I believe covers the information missing from the highest voted answer that could be very valuable to any who find this:

    For each of the following methods connect them with a count if you need any input to be accepted. (Assuming we are using vocal definitions of integers rather than 0-255, etc.)

    x.isdigit() works well for checking if x is an integer.

    x.replace('-','').isdigit() works well for checking if x is a negative.(Check - in first position)

    x.replace('.','').isdigit() works well for checking if x is a decimal.

    x.replace(':','').isdigit() works well for checking if x is a ratio.

    x.replace('/','',1).isdigit() works well for checking if x is a fraction.

提交回复
热议问题