How do you convert text to numeric in python?

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    In Python an strings can be converted into a integer using the built-in int() function. The int() function takes in any python data type and converts it into a integer.But use of the int() function is not the only way to do so. This type of conversion can also be done using thefloat() keyword, as a float value can be used to compute with integers.

    Below is the list of possible ways to convert an integer to string in python:

    1. Using int() function

    Syntax: int(string)

    Example:

    num = '10'

    print(type(num)) 

    converted_num = int(num)

    print(type(converted_num))

    print(converted_num + 20)

    As a side note, to convert to float, we can use float() in Python

    num = '10.5'

    print(type(num)) 

    converted_num = float(num)

    print(type(converted_num))

    print(converted_num + 20.5)

    2. Using float() function

    We first convert to float, then convert float to integer. Obviously the above method is better (directly convert to integer)

    Syntax: float(string)


    Example:

    a = '2'

    b = '3'

    print(type(a))

    print(type(b))

    a = float(a)

    b = int(b)

    sum = a + b

    print(sum)

    Output:

    class 'str'
    class 'str'
    5.0

    Note: float values are decimal values that can be used with integers for computation.


    Introduction

    Python allows you to convert strings, integers, and floats interchangeably in a few different ways. The simplest way to do this is using the basic str(), int(), and float() functions. On top of this, there are a couple of other ways as well.

    Before we get in to converting strings to numbers, and converting numbers to strings, let's first see a bit about how strings and numbers are represented in Python.

    Note: For simplicity of running and showing these examples we'll be using the Python interpreter.

    Strings

    String literals in Python are declared by surrounding a character with double (") or single quotation (') marks. Strings in Python are really just arrays with a Unicode for each character as an element in the array, allowing you to use indices to access a single character from the string.

    For example, we can access individual characters of these strings by specifying an index:

    >>> stringFirst = "Hello World!"
    >>> stringSecond = 'Again!'
    >>> stringFirst[3]
    'l'
    >>> stringSecond[3]
    'i'
    

    Numerics

    A numeric in Python can be an integer, a float, or a complex.

    Integers can be a positive or negative whole number. Since Python 3, integers are unbounded and can practically hold any number. Before Python 3, the top boundary was 231-1 for 32-bit runtimes and 263-1 for 64-bit runtimes.

    Floats have unlimited length as well, but a floating-point number must contain a decimal point.

    Complex numerics must have an imaginary part, which is denoted using j:

    >>> integerFirst = 23
    >>> floatFirst = 23.23
    >>> complextFirst = 1 + 23j
    

    Converting Strings to Numerics

    Using the int() Function

    If you want to convert a string to an integer, the simplest way would be to use int() function. Just pass the string as an argument:

    >>> x = "23"
    >>> y = "20"
    >>> z = int(x) - int(y)
    >>> z
    3
    

    This works as expected when you're passing a string-representation of an integer to int(), but you'll run in to trouble if the string you pass doesn't contain an integer value. If there are any non-numeric characters in your string then int() will raise an exception:

    >>> x = "23a"
    >>> z = int(x)
    Traceback (most recent call last):
      File "", line 1, in 
    ValueError: invalid literal for int() with base 10: '23a'
    

    This same exception will even be raised if a valid float string is passed:

    >>> x = "23.4"
    >>> z = int(x)
    Traceback (most recent call last):
      File "", line 1, in 
    ValueError: invalid literal for int() with base 10: '23.4'
    

    The int() function does have another useful feature than just converting strings to integers, it also allows you to convert numbers from any base to a base 10 integer. For example, we can convert the following binary string to a base 10 integer using the base parameter:

    >>> int('1101100', base=2)
    108
    

    The same can be done for any other base, like hexadecimal (base 16):

    >>> int('6C', base=16)
    108
    

    Using the float() Function

    Converting string literals to floats is done via the float() function:

    >>> x = "23.23"
    >>> y = "23.00"
    >>> z = float(x) - float(y)
    >>> z
    0.23000000000000043
    

    Notice that the resulting value is not entirely accurate, as it should just be 0.23. This has to do with floating point math issues rather than the conversion from string to number.

    The float() function offers a bit more flexibility than the int() function since it can parse and convert both floats and integers:

    Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

    >>> x = "23"
    >>> y = "20"
    >>> z = float(x) - float(y)
    >>> z
    3.0
    

    Unlike int(), float() doesn't raise an exception when it receives a non-float numeric value.

    However, it will raise an exception if a non-numeric value is passed to it:

    >>> x = "23a"
    >>> z = float(x)
    Traceback (most recent call last):
      File "", line 1, in 
    ValueError: could not convert string to float: '23a'
    

    While float() does not have the ability to convert non-base 10 numbers like int() does, it does have the ability to convert numbers represented in scientific notation (aka e-notation):

    >>> float('23e-5')
    0.00023
    >>> float('23e2')
    2300.0
    

    Using the complex() Function

    Converting string literals to complex numerics is done via the complex() function. To do so, the string must follow specific formatting. Particularly, it must be formatted without white spaces around the + or - operators:

    >>> x = "5+3j"
    >>> y = "3+1j"
    >>> z = complex(x) + complex(y)
    >>> z
    (8+4j)
    

    Having any extra spaces between the + or - operators will result in a raised exception:

    >>> z = complex("5+ 3j")
    Traceback (most recent call last):
      File "", line 1, in 
    ValueError: complex() arg is a malformed string
    

    Like the float() function, complex() is also more relaxed in the types of numbers it allows. For example, the imaginary part of the number can be completely omitted, and both integers and floats can be parsed as well:

    >>> complex("1")
    (1+0j)
    >>> complex("1.2")
    (1.2+0j)
    

    As you can see, however, this should not be used as a more flexible replacement for int/float since it automatically adds the imaginary part of the number to the stringified version.

    Converting Numerics to Strings

    Using the str() Function

    The str() function can be used to change any numeric type to a string.

    The function str() is available from Python 3.0+ since the strings in Python 3.0+ are Unicode by default. However, this is not true for Python versions below 3.0 - in which to achieve the same goal, the unicode() function is used:

    >>> str(23)   # Integer to String
    '23'
    >>> str(23.3) # Float to String
    '23.3'
    >>> str(5+4j) # Complex to String
    '(5+4j)'
    

    The nice thing about str() is that it can handle converting any type of number to a string, so you don't need to worry about choosing the correct method based on what type of number you're converting.

    Using the format() Function

    Another way of converting numerics to strings is using the format() function, which allows you to set placeholders within a string and then convert another data type to a string and fill the placeholders.

    To use the function, simply write a string followed by .format() and pass the arguments for the placeholders.

    Here's an example:

    >>> "My age is {}".format(21)
    'My age is 21'
    

    The arguments in the .format() function can also be referred to individually, using their positions or variable names:

    >>> "You get {product} when you multiply {1} with {0}".format(5.5, 3, product=16.5)
    'You get 16.5 when you multiply 3 with 5.5'
    

    Note that underneath the hood, the .format() function simply uses str() to convert the arguments to strings. So essentially this is a similar way of converting numbers to strings as the previous section, but .format() acts as a convenience function for formatting a string.

    Conclusion

    Python allows you to convert strings, integers, and floats interchangeably in a few different ways. The simplest way to do this is using the basic str(), int(), and float() functions. On top of this, there are a couple of other ways as well such as the format() function. Just keep in mind that the int(), float(), and complex() functions have their limitations and may raise exceptions if the input string isn't formatted exactly as they expect.

    How do I convert a string to a number?

    In Java, we can use Integer.valueOf() and Integer.parseInt() to convert a string to an integer..
    Use Integer.parseInt() to Convert a String to an Integer. This method returns the string as a primitive type int. ... .
    Use Integer.valueOf() to Convert a String to an Integer. This method returns the string as an integer object..

    How do you convert data type in Python?

    To convert between types, you simply use the type name as a function. There are several built-in functions to perform conversion from one data type to another. These functions return a new object representing the converted value.

    How do you convert string to integer in Python?

    To convert a string to integer in Python, use the int() function. This function takes two parameters: the initial string and the optional base to represent the data. Use the syntax print(int("STR")) to return the str as an int , or integer.