繁体   English   中英

Python:用字符串替换数值

[英]Python: Replace Numeric Value With String

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

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

顺便说一句,看来您的基本转换实际上并不会做您想要的。 您应该看看如何将任意基数的整数转换为字符串? 正确执行转换(例如,十六进制中包含字母AF,例如,您的代码未处理这些字母)。

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

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): ')]

请注意,如果x不是字典中的键, 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()来实现此.lower()

尝试

 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”)中。 然后,您可以在输出中使用此变量。

暂无
暂无

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

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