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

Python字符串数字提取排序求和 无字母场景校验问题求解

代码修改方案

以下是修改后可覆盖所有要求场景的完整代码:

string1 = input("Enter the string: ")
output_list = [] 
sum_total = 0
has_alpha = False
has_digit = False

for char in string1:
    if char.isalpha():
        has_alpha = True
    if char.isdigit():
        has_digit = True
        output_list.append(char)

if not has_alpha:
    print("There's no alphabet in the string.")
elif not has_digit:
    print("There's no digit in the string.")
else:
    output_list.sort()
    print(output_list)
    for i in output_list:
        sum_total += int(i)
    print(sum_total)

本次修改的核心调整点:

  • 移除了原代码中未使用的flag变量,新增has_alpha、has_digit两个布尔标记位,遍历字符串时同步识别是否存在字母、数字两类字符
  • 新增输入合法性校验逻辑,优先判断输入是否符合「同时包含字母和数字」的要求:不存在字母时直接输出示例2要求的提示文本,完全匹配测试场景
  • 只有输入合法时才执行数字排序、求和输出的逻辑,避免非法输入场景输出无效内容
  • 将原变量名sum改为sum_total,避免覆盖Python内置的sum()函数,减少潜在bug

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 16:15:02