如何在Python中生成指定起止点之间的自定义字符集字符串序列
Generate All Strings Between Two Values in Python (Custom Charset)
Got it, let's work through this problem step by step. You want to generate every string in sequence from a start value to an end value using the custom charset 0123456789abcdefABCDEF, right? Let's break down how to make this happen.
Approach
The key trick here is to treat each string as a number in a base-22 number system (since our charset has exactly 22 unique characters). Here's the plan:
- Map each character in the charset to a unique integer index (0 to 21) so we can convert strings to numeric values easily.
- Turn the start and end strings into their corresponding integer values using this mapping.
- Iterate from the start integer to the end integer, converting each number back into the string format with the reverse mapping.
- Make sure all output strings keep the original length (so we don't get shorter strings when converting smaller numbers).
Solution Code
def generate_string_range(start_str, end_str): # Define our custom character set charset = "0123456789abcdefABCDEF" char_to_idx = {char: idx for idx, char in enumerate(charset)} base = len(charset) str_length = len(start_str) # Make sure start and end strings are the same length if len(end_str) != str_length: raise ValueError("Start and end strings must have the same length") # Convert a string to its numeric equivalent def str_to_num(s): num = 0 for char in s: num = num * base + char_to_idx[char] return num # Convert a number back to the string format (fixed length) def num_to_str(num): result = [] for _ in range(str_length): result.append(charset[num % base]) num = num // base # Reverse to get the correct order (since we built it from right to left) return ''.join(reversed(result)) # Convert start and end to numbers start_num = str_to_num(start_str) end_num = str_to_num(end_str) # Handle invalid range if start_num > end_num: raise ValueError("Start string must come before end string in the charset sequence") # Generate all strings and join them with spaces output_strings = [num_to_str(num) for num in range(start_num, end_num + 1)] return ' '.join(output_strings) # Example usage matching your request if __name__ == "__main__": start = "22Ef" end = "FFFF" print(generate_string_range(start, end))
How It Works
- Character Mapping: We create a dictionary
char_to_idxthat links each character to its position in the charset (e.g.,'0' → 0,'a' → 10,'A' → 16,'F' → 21). - String to Integer: The
str_to_numfunction converts a string to an integer by treating each character as a digit in base-22. For example,"22Ef"calculates to:
(since(2 * 22³) + (2 * 22²) + (14 * 22¹) + (21 * 22⁰)'E'is index 14 and'f'is index 21) - Integer to String: The
num_to_strfunction reverses the process: it repeatedly divides the number by 22, uses the remainder to pick a character from the charset, then reverses the result to get the correct left-to-right order. - Range Generation: We convert the start and end strings to integers, loop through every number in between, convert each back to a string, and join all results with spaces like your example shows.
Quick Notes
- This solution assumes your start and end strings are the same length. If you need to handle variable lengths (like
"FFF"to"1000"), you'd need to add logic to pad shorter strings with leading characters from the charset. - The function will throw an error if the start string comes after the end string in the charset sequence—this prevents invalid ranges that don't make sense.
内容的提问来源于stack exchange,提问作者EL-AJI Oussama
相关产品推荐
相关产品推荐

