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

后端 未结 30 4746
暗喜
暗喜 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:32

    You can generalize the exception technique in a useful way by returning more useful values than True and False. For example this function puts quotes round strings but leaves numbers alone. Which is just what I needed for a quick and dirty filter to make some variable definitions for R.

    import sys
    
    def fix_quotes(s):
        try:
            float(s)
            return s
        except ValueError:
            return '"{0}"'.format(s)
    
    for line in sys.stdin:
        input = line.split()
        print input[0], '<- c(', ','.join(fix_quotes(c) for c in input[1:]), ')'
    

提交回复
热议问题