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

This instructional exercise depicts fluctuated techniques to convert a Python string to int and from an integer to a string. You may commonly need to complete such tasks in everyday programming. Consequently, it is ideal to realize them to compose higher packages.

Likewise, an integer may be addressed in entirely unexpected bases, so we’ll clarify that too in this distribution. Also, there happen to be circumstances in the spot transformation fizzles. Henceforth, it is ideal to mull over such conditions appropriately and can find a full reference given here with models.

In the most ideal way, will likely be useful if you will have some rudimentary data concerning the Python data types. If not, kindly go through the connected instructional exercise.

Python String to Int and Int to String Conversion

It is significant for a developer that knows about concerning entirely unexpected change systems. At the point when you take in or get data from an outside supply-like data, it very well may be an amount anyway in string design. Or on the other hand, for the most part, we use strings to show in a styled implies.

Afterward, with regards to controlling or changing the amount, then, at that point you certainly need to convert the string to an integer or in an appropriate kind. Thus, how about we currently perceive how to convert a Python string to int and analyze all +/ – ve circumstances?

Int() to Convert Python String to Int

Python supplies a normal integer (class ‘int’) to manage numeric tasks. It accompanies the int() constructor technique, which can be used for changing a string to int.

How about we attempt the int() act moving with the help of an occasion:

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

# Salary per year in string format
Salary_Per_Year = '1000000'

# Test the info kind of 'Salary Per Year' variable
print("Data Type of 'Salary_Per_Year': ".format(kind(Salary_Per_Year)))

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

#Again,take a look at the info kind of 'Salary Per Year' variable
print("Data Type of 'Salar_yPer_Year': ".format(kind(Salary_Per_Year)))

Below is the outcome after executing the above code:

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

Convert an Integer from Different Bases

The default base for integer kind qualities is 10. Nonetheless, in certain circumstances, the string can involve an amount in an unmistakable base separated from the ten.

A base or radix is the assortment of entirely unexpected digits or a combination of digits and letters {that a} arrangement of checking utilizes to signify numbers.

If you should realize extra concerning the possibility of a base, then, at that point allude to this – Base in Mathematics.

While changing such an amount, you need to specify the right base in the int() perform for a productive transformation. It will expect the following grammar:

#Syntax
int(input_str, base_arg)

The permitted shift for the base contention is from 2 to 36.

The level to see here is that the result would constantly be an integer with Base 10. Look at the underneath pattern code to unequivocally see Python string to int transformation from entirely unexpected bases.

"""
Example:
Description: 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
MACHINEID = int(MachineIdBase10, 10)
print("MachineID '' conversion from Base 10: ".format(MachineIdBase10, MACHINEID))

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

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

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.

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 below instance to perceive.

"""
Python Example:
 Desc:
 Handle string to int conversion error/exception
"""

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

try:
    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

try:
    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 on the code, you get the next outcome:

(*1*)

Python Int to String

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

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

examples:

"""
Python Example:
 Desc:
 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 Output

Key Notes

  • Typecasting is the method of changing an object from one kind to one another.
  • 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 a lack of information as the consumer does it by pressure.

Recommended Post:

Pramod Kumar Yadav is from Janakpur Dham, Nepal. He was born on December 23, 1994, and has one elder brother and two elder sisters. He completed his education at various schools and colleges in Nepal and completed a degree in Computer Science Engineering from MITS in Andhra Pradesh, India. Pramod has worked as the owner of RC Educational Foundation Pvt Ltd, a teacher, and an Educational Consultant, and is currently working as an Engineer and Digital Marketer.



Leave a Comment