Convert Python String to Int and Int to String in 1 Step – My programming school

This tutorial describes varied methods to convert Python string to int and from an integer to string. You might typically want to carry out such operations in day to day programming. Hence, it is best to know them to write higher packages.

Also, an integer might be represented in totally different bases, so we’ll clarify that too in this publish. And there occur to be situations the place conversion fails. Hence, it is best to contemplate such circumstances as properly and can discover a full reference given right here with examples.

By the best way, will probably be helpful if you will have some elementary data concerning the Python data types. If not, please do undergo the linked tutorial.

Python String to Int and Int to String Conversion

It is important for a programmer that he is aware of concerning the totally different conversion strategies. When you learn or obtain information from an exterior supply like information, it might be a quantity however in string format. Or generally, we use strings to show in a styled means.

Later, when it comes to manipulate or change the quantity, then you definately want to convert string to an integer or in an applicable kind. So, let’s now see how to convert a Python string to int and examine all +/-ve situations.

Int() to Convert Python String to Int

Python supplies a typical integer class (class ‘int’) to deal with numeric operations. It comes with the int() constructor methodology, which can be utilized for changing a string to int.

Let’s try the int() perform in motion with the assistance of an instance:

Python Example:
 Use Python int() perform to convert string to int

# Salary per yr in string format
SalaryPerYear = '1000000'

# Test the info kind of 'SalaryPerYear' variable
print("Data Type of 'SalaryPerYear': ".format(kind(SalaryPerYear)))

# Let's carry out string to int conversion
SalaryPerYear = int(SalaryPerYear)

# Again, take a look at the info kind of 'SalaryPerYear' variable
print("Data Type of 'SalaryPerYear': ".format(kind(SalaryPerYear)))

Below is the outcome after executing the above code:

Data Type of 'SalaryPerYear': <class 'str'>
Data Type of 'SalaryPerYear': <class 'int'>

Convert an Integer from Different Bases

The default base for integer kind values is 10. However, in some situations, the string can comprise a quantity in a distinct base apart from the ten.

A base or radix is the variety of totally different digits or a mixture of digits and letters {that a} system of counting makes use of to signify numbers.

If you might want to know extra concerning the idea of a base, then refer to this – Base in Mathematics.

While changing such a quantity, you want to specify the right base in the int() perform for a profitable conversion. It will assume the next syntax:

# Syntax
int(input_str, base_arg)

The allowed vary for the bottom argument is from 2 to 36.

The level to notice right here is that the outcome would all the time be an integer with Base 10. Check out the beneath pattern code to precisely perceive Python string to int conversion from totally different bases.

Python Example:
 Use Python int() perform to convert string to int from totally different bases

# Machine Id in string format
MachineIdBase10 = '10010'
MachineIdBase8 = '23432' # 10010 => base 8 => 23432
MachineIdBase16 = '271A' # 10010 => base 16 => 271A

# Convert machine id from base 10 to 10
MACHINE_ID = int(MachineIdBase10, 10)
print("MachineID '' conversion from Base 10: ".format(MachineIdBase10, MACHINE_ID))

# Convert machine id from base 8 (octal) to 10
MACHINE_ID = int(MachineIdBase8, 8)
print("MachineID '' conversion from Base 8: ".format(MachineIdBase8, MACHINE_ID))

# Convert machine id from base 16 (hexadecimal) to 10
MACHINE_ID = int(MachineIdBase16, 16)
print("MachineID '' conversion from Base 16: ".format(MachineIdBase16, MACHINE_ID))

When you execute the given code, it converts the strings (MACHINEIdBase) holding the identical quantity however in totally different base codecs. And the output worth of MACHINE_ID is all the time in the bottom 10.

Convert Python string to int from different bases

Check for Error/Exception in Conversion

It is additionally attainable to get an error or exception (WorthError) while changing a string to int. It normally occurs when the worth is not precisely a quantity.

For instance, you are attempting to convert a string containing a quantity formatted utilizing commas. Or it shops a hexadecimal worth, however you missed to pass the bottom argument.

So, you might want to deal with such errors and take some preventive actions. Please try the beneath instance to perceive.

Python Example:
 Handle string to int conversion error/exception

# Salary variable holds a quantity formatted utilizing commas
Salary = '1,000,000'

    print("Test Case: 1n===========n")
    numSalary = int(Salary)
except WorthError as ex:
    print(" Exception: n  ", ex)
    newSalary = Salary.substitute(',', '')
    print(" Action: ")
    numSalary = int(newSalary)
    print("  Salary (Int) after converting from String: ".format(numSalary))

# MachineId
MachineId = 'F4240' # 1,000,000 => base 16 => F4240

    print("nTest Case: 2n===========n")
    MACHINE_ID = int(MachineId)
except WorthError as ex:
    print(" Exception: n  ", ex)
    print(" Action: ")
    MACHINE_ID = int(MachineId, 16)
    print("  MACHINE_ID (Int) after converting from String: ".format(MACHINE_ID))

The instance consists of two take a look at circumstances. The first exhibits an error when the string comprises a formatted quantity. And the second fails due to incorrect base worth.

After working the code, you get the next outcome:


Python Int to String

There is one other Python customary library perform known as Str(). It merely takes a quantity worth and converts it to a string.

However, Python 2.7 additionally had a perform known as Unicode() that used to produce Unicode strings. But it isn’t out there in Python 3 or later.

Check out the next examples:

Python Example:
 Use Python str() perform to convert int to string

# Numeric Machine Id in Hexadecimal Format
MachineIdBase16 = 0x271A # 0x271A ==> 10010

# Convert numeric Machine Id to Integer
MACHINE_ID = str(MachineIdBase16)
print("nMachineID () conversion from Base 16: n".format(hex(MachineIdBase16), MACHINE_ID))
print("MachineIdBase16 type:  => Post CONVERT => MACHINE_ID type: n".format(kind(MachineIdBase16), kind(MACHINE_ID)))

Below is the output snippet after executing the above code:

Convert Python int to string
Convert Python Int to String Output

Key Notes

  • Typecasting is the method of changing an object from one kind to one other.
  • Python mechanically performs the conversion identified as Implicit Type Casting.
  • Python ensures that no information loss happens in kind conversion.
  • If you name capabilities to convert the kinds, then the method is known as Explicit Type Casting.
  • Explicit Casting might lead to lack of information as the consumer does it by pressure.

Suggested Reading

Source hyperlink

Python String to Int and Int to StringPython String to Int and Int to String,Python String to Int and Int to String,Python String to Int and Int to String,Python String to Int and Int to String,Python String to Int and Int to StringPython String to Int and Int to String

Have any Question or Comment?

Leave a Reply

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


You have successfully subscribed to myprogrammingschool

There was an error while trying to send your request. Please try again.

My Programming School will use the information you provide on this form to be in touch with you and to provide updates and marketing.