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
randrangebut adjust the upper bound to16: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
sizevariable is 0 (butrandrange(10,15)will never return 0, so this isn't the case) - You're accidentally passing an empty string for the
charsparameter when calling the function (your default value is fine, but double-check your function calls) - You're missing required module imports (
randomorstring). If your code doesn't haveimport randomandimport stringat the top, callingrandom.randrangeor accessingstring.ascii_letterswill throw aNameError. If this error is being silently caught (e.g., in atry/exceptblock 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
charscheck 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
相关产品推荐
相关产品推荐

