【问题标题】:How can I get Python to recognize comma as the decimal point in user input? [duplicate]如何让 Python 将逗号识别为用户输入中的小数点? [复制]
【发布时间】:2020-05-29 11:10:03
【问题描述】:

这里是超级初学者。

我正在关注使用 Python 自动化无聊的东西这本书,我决定制作一个小脚本来帮助我进行一些基本的百分比检查。我不想每次都打开 Excel。

所以脚本获取两个输入,一个旧价格和一个新价格,然后计算价格变化的百分比。我想我是对的。

一旦我尝试输入浮点数(这是正确的术语,是吗?)并且我在欧洲使用逗号,就会出现问题。

我找到了一个主题here 回答了类似的问题,但似乎存在关于是否调用 setlocale 的问题,并且(据我了解)它不涉及如何转换输入?

我的代码如下:

    def izracun_odstotkov():    #function to calculate the difference in % between original price and new price
    while True:
        try:
            prvotna_cena = float(input('Prosim vnesi prvotno ceno:')) #original price
        except ValueError:
            print('Oprosti, to ni veljavni podatek. Vnesi stevilko.')
            continue

        if prvotna_cena == 0:
                print('Prvotna cena ne more biti 0.')
        else:
            break

    while True:
        try:
            nova_cena = float(input('Prosim vnesi novo ceno:')) #new price
        except ValueError:
            print('Oprosti, to ni veljavni podatek. Vnesi stevilko.')
            continue
        else:
            break

    print(round((float (nova_cena)- float (prvotna_cena))/ float (prvotna_cena)*100, 2), '%')

while True:
    izracun_odstotkov() #This makes the script run over and over so the user can just keep checking the % changes.

【问题讨论】:

  • 也许您可以使用 float(input(some_prompt).replace(",", ".")) 之类的东西直接用点替换逗号?我确信有更优雅的方法可以做到这一点,但这个 hack 也应该可以完成这项工作。
  • 哦,原来如此。不过,some_prompt 是什么意思?抱歉,我还在习惯一切。
  • 哦,我只是将它用作您在示例中使用的 'Prosim vnesi prvotno ceno:' 之类的占位符。
  • 你好。这。 replace 方法非常适合输入。现在我试图弄清楚如何使脚本输出具有相同替换的百分比结果并不断收到类似 AttributeError 的错误:'float' object has no attribute 'replace' 'function' object has no attribute 'replace' 我唯一的原因也想在那里替换它,所以我可以使用 pyperclip 将结果存储在剪贴板中,然后将其粘贴到另一个程序中我需要的任何字段中。你对如何解决这个问题有什么建议吗?对不起:(
  • @JakeTae 抱歉,忘记在我上面的评论中标记你了。

标签: python floating-point decimal


【解决方案1】:

你可以使用替换方法:

prvotna_cena = float(input('Prosim vnesi prvotno ceno:').replace(',','.'))

【讨论】:

  • 谢谢。这确实得到了很多建议。我想对于这样的脚本来说,这是最简单的方法! :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-09-25
  • 1970-01-01
  • 2021-11-06
  • 2014-12-02
  • 1970-01-01
  • 1970-01-01
  • 2013-12-11
相关资源
最近更新 更多