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

randrange()在random_string()函数中失效及空字符串问题求助

Fixing Your Random String Function Issues

Let's break down what's going wrong here and fix it step by step:

1. Why the Length Isn't Matching Your Expectation

You used random.randrange(10, 15) to set the string length, but here's the catch: randrange uses a left-closed, right-open interval. That means it will only generate integers from 10 up to 14—never 15. To get lengths from 10 to 15 (inclusive), you have two solid options:

  • Use random.randint(10, 15) (this function is explicitly for closed intervals, so it includes both endpoints)
  • Or keep using randrange but adjust the upper bound to 16: random.randrange(10, 16)

2. Why You're Getting Empty Strings (~20% of the Time)

An empty string can only pop up here for a few specific reasons:

  • The size variable is 0 (but randrange(10,15) will never return 0, so this isn't the case)
  • You're accidentally passing an empty string for the chars parameter when calling the function (your default value is fine, but double-check your function calls)
  • You're missing required module imports (random or string). If your code doesn't have import random and import string at the top, calling random.randrange or accessing string.ascii_letters will throw a NameError. If this error is being silently caught (e.g., in a try/except block that returns an empty string on failure), that would explain the occasional empty results.

Fixed Code

Here's the corrected version of your function, with all issues addressed:

import random
import string

def random_string(chars=string.ascii_letters + string.digits):
    # Add a check to prevent empty chars from being passed accidentally
    if not chars:
        raise ValueError("The 'chars' parameter can't be an empty string")
    
    # Generate length from 10 to 15 (inclusive)
    size = random.randint(10, 15)
    
    # Build and return the random string
    return ''.join(random.choice(chars) for _ in range(size))

Verification

  • This function will consistently return strings between 10-15 characters long, matching your original requirement.
  • The chars check ensures you'll never get an empty string from invalid input (it'll throw a clear, actionable error instead).
  • As long as you have the necessary imports, there's no chance of silent failures leading to empty strings.

内容的提问来源于stack exchange,提问作者Zorgan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:30:14