Tutorial

Python String to Int, Int to String

Published on August 3, 2022
Default avatar

By Pankaj

Python String to Int, Int to String

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

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

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Pankaj

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
November 8, 2020

hellow i have a question this my activity its very defficult😊 here is the output using python write a program that accepts decimal integer and ask the user to what numeric literal conversion is. Test 1 Enter a number: 100 convert to - Type A binary B octal C hex): A In binary: 0b1100100 Test case 2 Enter a number: 31 convert to - Type A binary B octal C hex): C In hexadecimal: 1F thats the output! how to program that output

- Lesther Pontillas

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    October 30, 2020

    I’m trying to make an if statement that will find whether or not the item is a number in the string, if it is, it will take that number and repeat a function that many times. I’m really confused on how I would make this work

    - Joshua

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      March 14, 2020

      here 123 is an single number this doesn’t work for a = '1 2 3 ’ seperated by spaces how ???

      - Aakash

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        February 19, 2019

        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

        - Philip Freidin

          Try DigitalOcean for free

          Click below to sign up and get $200 of credit to try our products over 60 days!

          Sign up

          Join the Tech Talk
          Success! Thank you! Please check your email for further details.

          Please complete your information!

          Get our biweekly newsletter

          Sign up for Infrastructure as a Newsletter.

          Hollie's Hub for Good

          Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

          Become a contributor

          Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

          Welcome to the developer cloud

          DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

          Learn more
          DigitalOcean Cloud Control Panel