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

Python实现输入数字逐位英文拼写垂直换行输出的问题求助

解决逐位数字转英文并分行输出的问题

你的代码核心问题是用空格拼接每一位的英文结果,导致所有内容在一行显示。只需要把拼接的空格换成换行符\n,再处理掉多余的换行即可。

修改后的代码:

arr = ['Zero','One','Two','Three','Four','Five','Six','Seven','Eight','Nine']
 
def number_2_word(num):
    if num == 0:
        return ""
    else:
        small_ans = arr[num % 10]
        # 用换行符代替空格拼接每一位的英文
        ans = number_2_word(num // 10) + small_ans + "\n"
        return ans
 
num = int(input("Enter the number: "))
# 用strip()去除首尾多余的换行符,避免最后出现空行
print(number_2_word(num).strip())

关键修改说明:

  • 将原代码中拼接用的" "替换为"\n",让每一位数字对应的英文单独占一行。
  • 最后调用strip()是因为递归到num=0时返回空字符串,会导致结果末尾多一个换行,strip()可以移除首尾的空白字符,保证输出格式干净。

测试输入86时,输出符合预期:

Enter the number: 86
Eight
Six

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 08:50:31