Python:用字符串替换数值

时间:2018-12-25 00:31:46

标签: python string replace

我正在尝试用字符串替换用户输入的值,以使输出更清晰

我认为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”

2 个答案:

答案 0 :(得分:1)

顺便说一句,看来您的基本转换实际上并不会做您想要的。您应该查看TBN vectors才能正确进行转换(例如,十六进制中包含字母A-F,例如,您的代码未处理这些字母)。

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

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

这是怎么回事? input()从stdin行起。在交互式情况下,这意味着用户键入一些内容(希望是数字),然后按Enter。我们得到那个字符串。然后int将该字符串转换为数字。

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

base_name_to_base = {'binary': 2, 'octal': 8, 'hexadecimal': 16}
base = base_name_to_base[input('Choose a base (binary, octal, hexadecimal): ')]

请注意,如果base_name_to_base[x]不是字典中的键,则raise KeyError可能会失败(x)。因此,您要处理此问题(如果用户输入"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 ")。您可以通过在.lower()返回的字符串上调用.strip()input()来做到这一点。

答案 1 :(得分:1)

尝试

 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”,...)存储在某个变量(“ base_string”)中。然后,您可以在输出中使用此变量。