【问题标题】:Replacing Numbers If they are a certain Worth替换数字,如果它们是一定的价值
【发布时间】:2018-08-29 02:35:50
【问题描述】:

我正在尝试创建一个系统,如果一个数字大于 5 或​​等于 5,则将该数字替换为数字 7,如果一个数字小于 5,则将其替换为 2

例如

Number= 93591374 
Answer= 72772272

我不知道该怎么做。有什么帮助吗?对不起python新手

【问题讨论】:

  • 你肯定会混淆 digits (5, 7) 和 numbers (93591374)。请更新您的答案以消除困惑。

标签: python replace numbers


【解决方案1】:

您可以将输入作为字符串 char by char 循环,并在循环过程结束后将其转换为 int。

n = '93591374'
ret = ''

for x in n:  
    if int(x) >= 5:
        ret += '7'
    else:
        ret += '2'

ret = int(ret)
print(ret)

输出:

72772272

【讨论】:

    【解决方案2】:
    number = 93591374
    
    #convert number to a string
    str_num = str(number)
    
    #create a variable to hold your answer
    answer = ""
    
    #iterate over all characters in the number string
    for dig in str_num:
        #typecast the dig variable into an int, so we can use a logical operator (greater than or equal to)
        if int(dig) >= 5:
           #set the answer variable value to the current value plus a new '7' digit appended at the end
           answer += "7"
        #typecast the dig variable into an int, so we can use a logical operator (less than)
        elif int(dig) < 5:
            #set the answer variable value to the current value plus a new '2' digit appended at the end
            answer += "2"
    #print the resulting string of digits 
    print(answer)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-15
      • 1970-01-01
      • 1970-01-01
      • 2020-09-15
      • 1970-01-01
      • 2022-11-25
      • 1970-01-01
      相关资源
      最近更新 更多