Python:用字符串替换数值

2024-04-19 23:21:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用字符串替换用户输入的值,以使输出更干净

我认为if语句会有所帮助,但我不确定它如何与我的预期输出相匹配

 def main() :
    number = int(input("Enter your number: "))
    base = int(input("Convert to\n" \
    "   Binary[2] - Octal[8] - Hexadecimal[16]: "))

    if base == 2 :
        "binary"
     elif base == 8 :
        "octal"
    else:
        "hexadecimal"

    print("\n"+str(number) +" in "+ str(base) + " is: " + str(convert(number, 10, base)))


  def convert(fromNum, fromBase, toBase) :
    toNum = 0
    power = 0

    while fromNum > 0 :
        toNum += fromBase ** power * (fromNum % toBase)
        fromNum //= toBase
        power += 1
    return toNum

main()

我想要的是: 如果用户输入5作为他们的数字和2作为转换。输出将是: “二进制中的5是:101”


Tags: 用户numberconvertinputbaseifmaindef
2条回答

试试看

 def main() :
    number = int(input("Enter your number: "))
    base = int(input("Convert to\n" \
    "   Binary[2] - Octal[8] - Hexadecimal[16]: "))
    base_string = "None"        

    if base == 2 :
        base_string = "binary"
     elif base == 8 :
        base_string = "octal"
    else:
        base_string = "hexadecimal"

    print("\n {} in {} is: {}".format(str(number), base_string, str(convert(number, 10, base))))


  def convert(fromNum, fromBase, toBase) :
    toNum = 0
    power = 0

    while fromNum > 0 :
        toNum += fromBase ** power * (fromNum % toBase)
        fromNum //= toBase
        power += 1
    return toNum

main()

你的问题是if语句中的“二进制”部分。实际上,它对代码和输出都没有影响。您必须将文本表示(“binary”,…)存储在某个变量(“basestring”)中。然后可以在输出中使用此变量。在

顺便说一句,看起来你的基址转换并不能实现你想要的效果。您应该查看How to convert an integer in any base to a string?来正确地进行转换(例如,十六进制中有字母A-F,您的代码不处理这些字母)。在

要接受名称而不是数字,您需要更改以下代码行:

base = int(input("Convert to\n   Binary[2] - Octal[8] - Hexadecimal[16]: "))

这是怎么回事?input()从stdin取一行。在交互式的情况下,这意味着用户键入一些东西(希望是一个数字),然后按enter键。我们拿到绳子了。然后int将该字符串转换为数字。在

您的convert要求{}是一个数字。您希望像"binary"这样的输入对应于base = 2。实现这一点的一种方法是使用dict。它可以将字符串映射到数字:

^{pr2}$

注意,如果x不是dict中的一个键,base_name_to_base[x]可能会失败(raise KeyError),所以您想处理这个问题(如果用户输入"blah"怎么办?)公司名称:

while True:
    try:
        base = base_name_to_base[input('Choose a base (binary, octal, hexadecimal): ')]
        break
    except KeyError:
        pass

这将循环,直到我们达到中断(只有在索引到base_name_to_base中时才会发生这种情况)不会引发密钥错误。在

此外,您可能需要处理不同的大小写(例如"BINARY")或任意空白(例如" binary ")。您可以通过对input()返回的字符串调用.lower().strip()。在

相关问题 更多 >