【问题标题】:adding to a string based on the number of characters根据字符数添加到字符串
【发布时间】:2021-07-23 10:15:51
【问题描述】:

问题是要打印“那是一个非常非常……大的数字”,其中每个额外的数字都有一个“真的”(所以 15 将是“这是一个非常大的数字”,150 将是“那是一个非常非常大的数字”,1500 将是“这是一个非常非常非常大的数字”,依此类推。)

输入是一个整数,列出的唯一要求是代码应该正确运行任何整数,应该使用 while 循环来保持数字除以 10,并且应该使用 += 添加到字符串的末尾

x = input(("input an integer: "))
count = len(x)
y = int(x / 10)
countx = count - 1
print("that's a " + count("really") + " big number")

我真的不知道我做了什么,但我可以说这是不正确的

【问题讨论】:

  • 额外的数字是否被视为 0?
  • count 是一个数字。通过将其称为带有count("really") 的函数,您不清楚您的意图。

标签: python python-3.x for-loop while-loop


【解决方案1】:

试试这个

x = int(input("enter an integer"))
print("that's a " + 'really '*(len(str(x))-1) + " big number")

如果您想更正您的功能,请使用此

x = input(("input an integer: "))
count = len(x)
y = int(x) / 10
countx = count - 1
print("that's a " + countx*" really" + " big number")

【讨论】:

    【解决方案2】:

    试试这个。它找出给定数字中有多少个尾随零,并据此创建一定数量的really's

    x = input(("input an integer: "))
    count = int(len(x) - len(x.rstrip('0')))
    if count == 0:count = 1
    really = "really "*count
    print(f"that's a {really} big number")
    

    【讨论】:

    • should use a while loop to keep dividing the number by 10 and should use += to add onto the end of a string
    • 这是一个作业
    • 如果您有更好的想法,请创建一个答案。
    • 也说15 would be "that's a really big number",您的代码为15 提供that's a big number
    【解决方案3】:

    试试这个。使用 while 循环将数字除以 10 并使用 += 添加到字符串中。您将需要获取一个字符串变量,然后随着计数的增加附加到它。根据您提到的条件,循环将一直运行到 number >= 10。

    x = int(input(("input an integer: ")))
    str=""
    while x>=10:
        x=x//10
        str+="really "
    print("that's a " + str + "big number")
    

    【讨论】:

    • @Mark 是的,没有使用 count=0。我忘了删除它。
    【解决方案4】:

    添加了您在问题中所述的 while 循环

    strVar = ""
    y = 0
    length = 0
    cnt = 0
    finished = False
    num = input("Type a number: ")
    
    while not finished:
        y = int(num)//10
        length = int(len(str(y)))
        if length <= cnt:
            finished = True
        else:
            strVar += " really"
    
        cnt += 1
        
    print("That's a" + strVar + " big number!")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-16
      相关资源
      最近更新 更多