You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何改进Python程序,实现输入为浮点数时不计算字符串长度?

Fixing Float Detection in Your String Length Calculator

Hey there! Let's sort out that issue where your code isn't properly handling float inputs. The problem with your current find(".") check is that it doesn't account for edge cases like inputs starting with a dot (.123), ending with a dot (123.), or even invalid multi-dot strings (12.34.56). Plus, bool(len1.find(".")) returns False when the dot is at index 0, so those leading-dot floats slip through the cracks.

The Most Reliable Fix: Try-Except Type Conversion

The cleanest way to detect valid integers and floats is to let Python handle the type checking natively with a try-except block. This method catches all valid numeric formats (including negatives like -456 or -78.9) and avoids false positives from invalid dot-containing strings.

Here's your revised code:

def strlength(string):
    return len(string)

user_input = input("Enter any string: ")

try:
    # Attempt to convert input to a float
    numeric_value = float(user_input)
    # Check if the float is actually an integer
    if numeric_value.is_integer():
        print("Integers cannot have length!")
    else:
        print("Float numbers cannot have length!")
except ValueError:
    # If conversion fails, it's a non-numeric string—calculate its length
    print(strlength(user_input))

Why This Works:

  • Valid Numeric Inputs: Any input that can be converted to a float (like 123, 45.67, .89, 100., -12.34) will trigger the try block. We then check if it's an integer using is_integer() to give the correct message.
  • Non-Numeric Strings: Inputs like "hello", "abc123", or "12a34" will fail the float conversion, fall into the except block, and have their length calculated as expected.
  • Fixes Your Original Edge Cases: Inputs like .5 or 67. are now correctly identified as floats, whereas your old code would have treated them as regular strings.

Alternative: Regex Pattern Matching

If you prefer to avoid try-except blocks, you can use a regular expression to match valid integer and float formats. This gives you more control over what counts as a "numeric" input:

import re

def is_valid_number(s):
    # Regex pattern matches integers, floats, negatives, and leading/trailing dots
    number_pattern = r'^[-+]?(\d+(\.\d*)?|\.\d+)$'
    return re.match(number_pattern, s) is not None

def strlength(string):
    return len(string)

user_input = input("Enter any string: ")

if is_valid_number(user_input):
    if '.' in user_input:
        print("Float numbers cannot have length!")
    else:
        print("Integers cannot have length!")
else:
    print(strlength(user_input))

Note on Your Original Code

Your initial isdigit() check only works for non-negative integers (e.g., -123 would return False and be treated as a string). Both solutions above fix this by handling negative numbers correctly.

内容的提问来源于stack exchange,提问作者Balu Mahesh TV

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:32:05