How to replace all ‘0’ with ‘5’ in an input Integer in Python

After this tutorial, you will be learned how to replace all ‘0’ with ‘5’ in an input integer in Python. This tutorial will show you 2 simple methods that are available in Python.

Method 1

Algorithm:

  • Get the input as an integer from the user.
  • Traverse the number digit by digit.
  • If  ‘0’ is found, then replace it with ‘5’.
  • Finally, print the integer.

Let’s take a look at the example.

def convertRec(no):  
    if(no==0): 
       return 0
    digit=no%10
    if(digit==0): 
        digit=5 
    return int(convertRec(no//10))*10+digit
def convert(no): 
    if(no==0): 
        return 5
    else: 
        return convertRec(no)  
no=int(input("Enter the integer:"))
print("Converted integer:",convert(no))

Input:

Enter the integer:2003

Output:

Converted integer: 2553

From the above sample input and output, you can see that all the ‘0’ in an input integer is replaced with ‘5’ in the output.

Method 2

This is another simple method for replacing all the ‘0’ with ‘5’ in an integer input.

Let’s have a look at the program.

n=int(input("Enter the number:"))
n=str(n)
n2=n.replace('0','5')
n2=int(n2)
print("Converted number:",n2)

This method works as follows.

  1. Get the input as an integer from the user.
  2. Then convert the integer to string using str() method.
  3. Replace all the ‘0’ with ‘5’ using replace() method.
  4. After that convert the string to an integer using int() method.
  5. Finally, print the converted integer as output.

Methods used:

1.Str()

  • Converts the specified into a string.
  • It takes an object as an argument and returns a string.
  • Syntax: str(object)

2.replace()

  • Replaces the old word/letter with a new word/letter.
  • It takes 3 arguments: old, new and count(optional).
  •  Syntax: string.replace(old,new,count)

3.int()

  • Converts the specified value into an integer.
  • It takes the value as an argument and returns an integer value.
  • Syntax: int(value)

Input:

Enter the number:1003

Output:

Converted number: 1553

I hope that this tutorial is useful.

Leave a Reply

Your email address will not be published. Required fields are marked *