Python String to Int, Int to String

Filed Under: Python

In this tutorial, we will learn how to convert python String to int and int to String in python. In our previous tutorial we learned about Python List append function.

Python String to Int

If you read our previous tutorials, you may notice that at some time we used this conversion. Actually, this is necessary in many cases. For example, you are reading some data from a file, then it will be in String format and you will have to convert String to an int.

Now, we will go straight to the code. If you want to convert a number that is represented in the string to int, you have to use int() function to do so. See the following example:


num = '123'  # string data

# print the type

print('Type of num is :', type(num))

# convert using int()

num = int(num)

# print the type again

print('Now, type of num is :', type(num))

The output of the following code will be


Type of num is : <class 'str'>
Now, type of num is : <class 'int'>
Python String To Int

Python String To Int

Converting String to int from different base

If the string you want to convert into int belongs to different number base other that base 10, you can specify the base for conversion. But remember that the output integer is always in base 10. Another thing you need to remember is that the given base must be in between 2 to 36. See the following example to understand the conversion of string to int with the base argument.


num = '123'
# print the original string
print('The original string :', num)

# considering '123' be in base 10, convert it to base 10

print('Base 10 to base 10:', int(num))

# considering '123' be in base 8, convert it to base 10

print('Base 8 to base 10 :', int(num, base=8))

# considering '123' be in base 6, convert it to base 10

print('Base 6 to base 10 :', int(num, base=6))

The output of the following code will be

Example of Python String to Int conversion

Python Convert String To Int Base

Python Convert String To Int With Base

ValueError when converting String to int

While converting from string to int you may get ValueError exception. This exception occurs if the string you want to convert does not represent any numbers.

Suppose, you want to convert a hexadecimal number to an integer. But you did not pass argument base=16 in the int() function. It will raise a ValueError exception if there is any digit that does not belong to the decimal number system. The following example will illustrate this exception while converting a string to int.


"""
    Scenario 1: The interpreter will not raise any exception but you get wrong data
"""
num = '12'  # this is a hexadecimal value

# the variable is considered as decimal value during conversion
print('The value is :', int(num))

# the variable is considered as hexadecimal value during conversion
print('Actual value is :', int(num, base=16))

"""
    Scenario 2: The interpreter will raise ValueError exception
"""

num = '1e'  # this is a hexadecimal value

# the variable is considered as hexadecimal value during conversion
print('Actual value of \'1e\' is :', int(num, base=16))

# the variable is considered as decimal value during conversion
print('The value is :', int(num))  # this will raise exception

The output of the above code will be:


The value is : 12
Actual value is : 18
Actual value of '1e' is : 30
Traceback (most recent call last):
  File "/home/imtiaz/Desktop/str2int_exception.py", line 22, in 
    print('The value is :', int(num))  # this will raise exception
ValueError: invalid literal for int() with base 10: '1e'
Python String To Int ValueError

Python String To Int ValueError

Python int to String

Converting an int to string requires no effort or checking. You just use str() function to do the conversion. See the following example.


hexadecimalValue = 0x1eff

print('Type of hexadecimalValue :', type(hexadecimalValue))

hexadecimalValue = str(hexadecimalValue)

print('Type of hexadecimalValue now :', type(hexadecimalValue))

The output of the following code will be:


Type of hexadecimalValue : <class 'int'>
Type of hexadecimalValue now : <class 'str'>
Python Int To String Conversion

Python Int To String Conversion

That’s all about Python convert String to int and int to string conversion.

Reference: Python Official Doc

Comments

  1. Philip Freidin says:

    Two minor corrections:
    (1) You wrote: “But remember that the output integer is always in base 10”

    The output of int() is an integer, stored in the computer’s native format for numbers, binary.
    By default, when printing out variables or results of type int, they are printed in decimal

    (2) You wrote: “Another thing you need to remember is that the given base must be in between 2 to 32.”

    the correct range is base 2 to base 36

    3) A suggestion: The industry standard for decades for base 16 is “hexadecimal” , I have never seen
    Hexa as an alternative

    4) As an alternative to a block of code followed by a block of output, maybe a screen capture of the examples and results as shown in an IDE such as Idle., so that the results are right next to the example statements

    1. Pankaj says:

      1. Yes, everything in a computer is stored in binary format.
      2. Thanks, corrected the typo.
      3. Changed hexa to hexadecimal at few places, thanks for the suggestion.
      4. Added few images from the IDLE as you suggested.

      Appreciate the feedback, will follow them in other tutorials too.

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages