Tutorials  /  Python

Python String to Int, Int to String Conversion Guide

Ccentron Redaktion · February 2024 ·4 min read ·Python, Tutorial

In this tutorial, we will learn how to convert python String to int and int to String in python.

VM

Try it yourself: cloud servers from €3.12/month

ccloud³ VMs from German data centers – deployed in seconds, billed by the hour, with a €200 starting credit for new accounts. Launch a server →

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:

Python
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

Code
Type of num is : <class 'str'>
  Now, type of num is : <class 'int'>

Converting String to Int from Different Base

If the string you want to convert into int belongs to a different number base other than 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.

Python
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

Code
The original string : 123
   Base 10 to base 10 : 123
   Base 8 to base 10 : 83
   Base 6 to base 10 : 51

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.

Python
"""
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:

Python
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 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.

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

Code
Type of hexadecimalValue : <class 'int'>
Type of hexadecimalValue now : <class 'str'>

Conclusion

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

Jetzt 200 € Guthaben sichern

Testen Sie Ihr Setup auf ccloud³

Registrieren Sie sich in der ccloud³ und erhalten Sie 200 € Startguthaben für Ihr Projekt – z. B. für eine PostgreSQL-VM mit automatischen Backups.

centron Redaktion Technische Redaktion

Das Redaktionsteam von centron schreibt Anleitungen aus dem Betriebsalltag: getestet auf unserer eigenen Plattform, betrieben im Rechenzentrum in Hallstadt bei Bamberg.

Kategorie Python
Teilen
Noch offene Fragen?

Unser Team hilft Ihnen bei Ihrem konkreten Setup weiter – von Menschen, die die Plattform selbst betreiben.

War dieses Tutorial hilfreich?

Ihre Antwort wird anonym gespeichert und hilft uns, die Tutorials zu verbessern.

Kommentare

Noch keine Kommentare – stellen Sie die erste Frage zu diesem Tutorial.

Zum Kommentieren anmelden

Kommentare stehen centron-Kunden offen. Melden Sie sich in Ihrem Konto an, um eine Frage zu diesem Tutorial zu stellen.

Weiterlesen

Das könnte Sie auch interessieren

Jetzt kostenlos anfangen

Melden Sie sich an und erhalten Sie in den ersten 60 Tagen ein Guthaben von 200 € bei centron.

Dieses Werbeangebot gilt nur für neue Konten. Angebot ausschließlich für Gewerbetreibende.

Jetzt loslegen Sales kontaktieren