【问题标题】:String Slicing with If?使用 If 进行字符串切片?
【发布时间】:2014-09-25 04:20:45
【问题描述】:

本学期开始了 Python 课程,但目前的作业遇到了问题。到现在翻遍了课堂上的例子和练习,没有找到任何东西。

Q1) 固定

aN = raw_input("Enter a number with decimals")
bN = raw_input("Enter a binary number, 2 to 4 digits in length")

if (bN[-1] == 1):
    print "The binary number was odd so your number will contain 2 decimals"
    print "The number is now",aN[0:4],

elif (bN[-1] == 0):
    print "The binary number was even so your number will contain 1 decimal"
    print "The number is now",bN[0:3]

我希望它能够打印出两个语句,每个结果一个。如果输入的二进制数以“1”结尾,它会输出带有 2 个小数的 N,如果输入的二进制数以“0”结尾,它会输出带有 1 个小数的 N。

当它运行时,它在显示用户输入的 bN 值后什么都不做

Q2) 有没有更好的方法来查找小数点后的数字?切片仅在数字

edit) 对指出字符串的人说,我完全忘记了:(

aN = raw_input("Enter a number with decimals")
bN = raw_input("Enter a binary number, 2 to 4 digits in length")

if (float(bN[-1]) == 1):
    print "The binary number was odd so your number will contain 2 decimals"
    print "The number is now",aN[0:4],

elif (float(bN[-1]) == 0):
    print "The binary number was even so your number will contain 1 decimal"
    print "The number is now",aN[0:3]

如果有人能回答第二个问题,那就太好了。

【问题讨论】:

  • 你所说的“吐出带 2 位小数的 N”是什么意思?你能给出一个 aN 和 bN 的输入示例,以及预期的输出吗?还有你的代码的输出。
  • 假设用户在被要求输入带小数 (aN) 的数字时输入 1.23456,在被要求输入二进制数 (bN) 时输入 11。二进制数的最后一位是 1,因此现在将 aN 作为 1.23 返回给用户。如果二进制数是 0 而不是 1,则返回给用户的数字将是 1.2
  • 1 == '1' if bn[-1] == '1':等等。

标签: python string if-statement


【解决方案1】:

假设 aN 总是至少有 1 位小数,这应该是可行的。您可以使用find() 来定位“.”。对于小数。

aN = raw_input("Enter a number with decimals")
bN = raw_input("Enter a binary number, 2 to 4 digits in length")

if (bN[-1] == "1"):
    print "The binary number was odd so your number will contain 2 decimals"
    print "The number is now", aN[:aN.find(".")+3]

elif (bN[-1] == "0"):
    print "The binary number was even so your number will contain 1 decimal"
    print "The number is now", aN[:aN.find(".")+2]

例子:

>>> aN
'1.12345'
>>> bN
'11'
>>> if (bN[-1] == "1"):
...     print "The binary number was odd so your number will contain 2 decimals"
...     print "The number is now", aN[:aN.find(".")+3]
... elif (bN[-1] == "0"):
...     print "The binary number was even so your number will contain 1 decimal"
...     print "The number is now", aN[:aN.find(".")+2]
...
The binary number was odd so your number will contain 2 decimals
The number is now 1.12

【讨论】:

    【解决方案2】:

    raw_input() 将输入作为字符串。在您的 if 条件中,您正在将字符串与整数进行比较。让你的if 像这样,

    if float(bN[-1]) == 1:
        print "The binary number was odd so your number will contain 2 decimals"
        print "The number is now %.2f" % float(aN)
    
    elif float(bN[-1]) == 0:
        print "The binary number was even so your number will contain 1 decimal"
        print "The number is now", bN[0:3]
    

    如果要打印小数点后2位,可以按照这个方法。

    【讨论】:

      猜你喜欢
      • 2021-03-12
      • 2012-07-13
      • 2017-09-28
      • 2020-05-04
      • 2012-12-25
      • 2014-07-08
      • 1970-01-01
      • 1970-01-01
      • 2020-11-27
      相关资源
      最近更新 更多