Замена чисел, если они стоят - PullRequest
0 голосов
/ 29 августа 2018

Я пытаюсь создать систему, в которой если число больше 5 или равно 5, то заменить это число на число 7, а если число меньше 5, то заменить его на 2

Например

Number= 93591374 
Answer= 72772272

Я не знаю, как именно это сделать. Любая помощь? Извините новичок в питоне

Ответы [ 2 ]

0 голосов
/ 29 августа 2018
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)
0 голосов
/ 29 августа 2018

Вы можете зациклить ввод как строковый символ на символ и преобразовать его в int после завершения цикла.

n = '93591374'
ret = ''

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

ret = int(ret)
print(ret)

ВЫВОД:

72772272
...