• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

Python String to Int Conversion & Vice-Versa [ Int to String ]

October 20, 2020 by javainterviewpoint Leave a Comment

In this tutorial, we will learn how to convert Python String to Int and vice-versa (Python Int to String). We will also explore the how-to convert String into an int with different bases and the possible conversion errors.

Python String to Int Conversion

Python String to Int Conversion

 

It is crucial for a developer to know the different Python Data types and conversions between them. Let’s take Python String to Int conversion itself, whenever we get the input from the user we typically use the input() function

The input() function reads a data entered by the user and converts it into a string and returns it. Even though the user has entered a numeric value, it will be automatically converted to String by Python, which cannot be used directly for any manipulation.

For example, if we want to divide the number entered by the user by 2.

>>> num = input("Enter a number : ")
Enter a number : 10
>>> num
'10'

The value stored inside num is not an integer 10 but the string ’10’. Let’s check the type of num for a confirmation.

>>> type(num)
<class 'str'>

If we try to divide the num by 2, we will get an Unsupported operand type error.

>>> print( num /2)
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in 
    print( num /2)
TypeError: unsupported operand type(s) for /: 'str' and 'int'

We cannot perform division operation on a String. So we need to perform the type conversion into the corresponding data type. Let’s limit it to int for now.

Using int() function to convert Python String to Int

For integer related operation, Python provides us with int class. We can use the int() function present in the int class to convert Python String to Int.

The int() function comes in two flavors

  • int(x) – Returns the integer objects constructed from the argument passed, it returns 0 if no argument is passed. It will create an integer object with the default base 10 (decimal).
  • int (x, base) – This method also returns the integer object with the corresponding base passed as the argument.

Let’s try to fix the issue which has happened in the above code. All we need to do is to just pass the num variable to the int() function to get it converted to an integer.

>>> num = int(num)
>>> type(num)
<class 'int'>
>>> print(num /2)
5.0

Converting to different Bases

We are able to successfully convert a string to an integer using the int() function, which is of base 10.

Let’s try to convert the String to different bases other than decimal such as binary (base 2), octal (base 8) and hexadecimal (base 16)

>>> val = '1101'
>>> base2int = int(val, 2)
>>> base2int
13
>>> val = '13'
>>> base8int = int(val, 8)
>>> base8int
11
>>> val = '1A'
>>> base16int = int(val, 16)
>>> base16int
26

Optionally we can also pass the String with the prefix for each base.

  • ‘0b’or ‘0B’ for binary
  • ‘0o’ or ‘0O’ for octal
  • ‘0x’ or ‘0X’ for hexadecimal
>>> prefixedVal = '0b110'
>>> base2int = int(prefixedVal, 2)
>>> base2int
6
>>> prefixedVal = '0o11'
>>> base8int = int(prefixedVal, 8)
>>> base8int
9
>>> prefixedVal = '0xB'
>>> base16int = int(prefixedVal, 16)
>>> base16int
11

Conversion Errors

Not all String can be converted into an integer. Below are some of the possible scenarios where int() function will throw an error.

1. Non-Numeric Characters

Whenever there is a non-numeric character in the String. We will get ValueError

>>> val = '15b'
>>> val = int(val)
Traceback (most recent call last):
  File "<pyshell#11>", line 1, in 
    val = int(val)
ValueError: invalid literal for int() with base 10: '15b'

2. Floating Point String

Similarly, we cannot convert a floating-point string to an integer, and we will get the same ValueError

>>> num = '17.7'
>>> num = int(num)
Traceback (most recent call last):
  File "<pyshell#13>", line 1, in 
    num = int(num)
ValueError: invalid literal for int() with base 10: '17.7'

3. Comma in Numbers

It is quite common to represent a number with a comma in Math, but the same cannot be applied in the computer world. If a number has a comma in it, then the int() function will throw an error.

>>> commaVal = '12,34,567'
>>> val = int(commaVal)
Traceback (most recent call last):
  File "<pyshell#15>", line 1, in 
    val = int(commaVal)
ValueError: invalid literal for int() with base 10: '12,34,567'

But, with a simple workaround, we can overcome this issue. We need to replace the comma with a blank before converting to integer

>>> val = int(commaVal.replace(",", ""))
>>> val
1234567

4. Invalid ranges

There is a specific allowed range for each base,

  • Binary (base 2) can have only o and 1
  • Octal (base 8) can have only values between 0 to 7
  • Hexadecimal (base 16) can have only values between 0 to 7 and A to F

We have to adhere to the specified ranges, if not we will get ValueError

>>> val = '123'
>>> base2int = int(val, 2)
Traceback (most recent call last):
File "<pyshell#1>", line 1, in
base2int = int(val, 2)
ValueError: invalid literal for int() with base 2: '123'

For Binary base only 0 and 1 are allowed, we have used 2,3, and hence we will get ValueError

>>> val = '8'
>>> base8int = int(val, 8)
Traceback (most recent call last):
File "<pyshell#5>", line 1, in
base8int = int(val, 8)
ValueError: invalid literal for int() with base 8: '8'

Octal allows the range of 0 to 7 Since ‘8’ is not a valid octal range. We are getting the error.

>>> val = 'H'
>>> base16int = int(val, 16)
Traceback (most recent call last):
File "<pyshell#7>", line 1, in
base16int = int(val, 16)
ValueError: invalid literal for int() with base 16: 'H'

HexaDecimal allows 0 to 7 and A to F, ‘H’ is not a valid range for the base 16.

Python Int to String Conversion

Converting a Python Int to String is pretty straight forward, we just need to pass the integer to the str() function. We don’t have to worry about the type of number or its bases.

>>> num = 13
>>> strNum = str(num)
>>> strNum
'13'
>>> binaryNum = '0b1101'
>>> strBinaryNum = str(binaryNum)
>>> strBinaryNum
'0b1101'
>>> hexNum = '0xA12'
>>> strHexNum = str(hexNum)
>>> strHexNum
'0xA12'

Happy Learning!!

Filed Under: Java Tagged With: Int to String, int() function, integer base, Python Int to String, Python String to Int, str() function, String to Int

Leave a Reply Cancel reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·