如果有一定价值,请替换数字

时间:2018-08-29 02:35:51

标签: python replace numbers

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

例如

Number= 93591374 
Answer= 72772272

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

2 个答案:

答案 0 :(得分:0)

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

n = '93591374'
ret = ''

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

ret = int(ret)
print(ret)

输出:

72772272

答案 1 :(得分:0)

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)