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

Python实现input输入未知长度字符串的大小写全排列方法

字符串大小写全排列实现方案

以下两种方案均支持任意长度的输入字符串,无需硬编码多层循环:

方案1:使用itertools.product实现(推荐,代码简洁)

核心逻辑是为每个字符生成大小写两种状态的元组,再通过笛卡尔积得到所有排列组合:

import itertools

# 获取用户输入
input_str = input("请输入字符串:").strip()
# 每个字符生成(大写, 小写)元组,组成列表
char_options = [(c.upper(), c.lower()) for c in input_str]
# 生成所有组合并输出
for combination in itertools.product(*char_options):
    print(''.join(combination))

方案2:递归实现(无需依赖额外标准库)

通过递归逐层处理每个字符的大小写状态,拼接得到所有结果:

def generate_permutations(current_str, remaining_chars, results):
    if not remaining_chars:
        results.append(current_str)
        return
    # 处理当前字符的大写情况
    generate_permutations(current_str + remaining_chars[0].upper(), remaining_chars[1:], results)
    # 处理当前字符的小写情况
    generate_permutations(current_str + remaining_chars[0].lower(), remaining_chars[1:], results)

# 获取用户输入
input_str = input("请输入字符串:").strip()
results = []
generate_permutations("", input_str, results)
# 输出所有结果
for res in results:
    print(res)

效果示例

如果用户输入ab,两种方案都会输出如下4种排列:

AB
Ab
aB
ab

内容的提问来源于stack exchange,提问作者mehrshad.afzal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 07:24:06