简体   繁体   English

Python-将数字更改为单词的最简单方法

[英]Python - Easiest way to change numbers to words

I know that I can use num2words , but for some reason I just cant think of how to have the user input a number say "197" and it come out with "one nine seven" instead of One Hundred Ninety Seven". All the ones I have seen so far change it into the actual number they input, while I just need the exact numbers they input printed. Sorry for my lack of knowledge in Python, literally just getting started and a little confused. I am using this as a skeleton for it currently, but it can only print up to 9 as I am still learning. 我知道我可以使用num2words ,但是出于某种原因,我只是想不出如何让用户输入数字“ 197”,而结果却是“一九七”而不是“一百零九十七”。到目前为止,我已经看到将其更改为他们输入的实际数字,而我只需要输入他们输入的确切数字,抱歉,由于我对Python缺乏了解,从字面上看才刚刚起步并有些困惑,我将其用作框架目前,它最多只能打印9张,因为我仍在学习。

import math

number = int(input("Enter number to print: "))

number_list = ["zero","one","two","three","four","five","six","seven","eight","nine"]

if number <= 9:
    print(number_list[number].capitalize())

Have you tried map? 您尝试过地图吗?

    input_number = input('Enter a number to print: ')
    number_strings = ['zero', 'one', 'two', 'three',
                      'four', 'five', 'six', 'seven',
                      'eight', 'nine']

    output_list = list(map(lambda x: number_strings[int(x)], input_number))

    print(' '.join(output_list))

With number_list defined as you have it above, you can do: 使用number_list定义的number_list ,您可以执行以下操作:

number = str(input("Enter number to print: "))

for digit in number:
    print(number_list[int(digit)], end=" ")

which prints the digits one at a time. 一次打印一位数字。 The end parameter dictates that a space should be printed after each digit. end参数指示在每个数字后应打印一个空格。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM