Home » Easy Ways To Convert String To Int Python

Easy Ways To Convert String To Int Python

Last updated on December 24, 2020 by

Sometimes, Python developers get confused to handle data types while they have lots of code and some circumstances. So sometimes, they need to convert one data type to another. In this article, we will learn how to convert string to int Python. Bare with me guys.

Table of Contents
1. Using Int() Function
2. Convert All Strings In A List Using map() Function In Python
3. Convert All Strings In A List Using List Comprehensions In Python
4. Using Fastnumbers Python Third-Party Module
5. Create Own Function In Python
6. Python Convert Comma-Separated String Number

Different Ways To Convert String To Int Python

The int() function is used to convert a string, number, float to an integer. If no argument pass then it will return 0. If you add a floating-point number in int() then it will return only a number after removing the decimal part. Let’s see how to do that.

01 Using Int() Function

In Python to convert a string to an integer, use the int() function. This function takes two parameters: the first one is required and takes a string and the second one is base and it’s optional.

Base argument is a number representing the number format.

Syntax:

int("STR", base)

Example:

myString = '77'

myString = int(myString)

print(myString)

#Output: 77

02 Convert All Strings In A List Using map() Function In Python

The map() function is used to execute a specified function for each item in an iterable. Let’s see how to convert the string list to the integer list.

If you are using Python version 2 then use below code:

cards = [ '7', '10', '5', '4', '1', '10' ]

convertedCards = map(int, cards)

print( convertedCards )

#output: [7, 10, 5, 4, 1, 10]

If you are using Python version 3 then use below code:

cards = [ '7', '10', '5', '4', '1', '10' ]

convertedCards = list(map(int, cards))

print( convertedCards )

#output: [7, 10, 5, 4, 1, 10]

03 Convert All Strings In A List Using List Comprehensions In Python

Python List Comprehensions is a simple way of creating a new list after performing some operations on it. It’s similar as we are performing operations in the loop and make a new list. Let’s see how to use it to convert all strings.

cards = [ '7', '10', '5', '4', '1', '10' ]

convertedCards = [int(i) for i in cards]

print( convertedCards )

#output: [7, 10, 5, 4, 1, 10]

04 Using Fastnumbers Python Third-Party Module

The fastnumbers module provides different functions that made conversion task very easy. Let’s have a look.

>>> from fastnumbers import fast_real
>>> fast_real('56')
56
>>> fast_real('56.0')
56
>>> fast_real('56.0', coerce=False)
56.0
>>> fast_real('56.07')
56.07
>>> fast_real(56.07)
56.07
>>> fast_real(56.0)
56
>>> fast_real(56.0, coerce=False)
56.0
>>>
>>>

05 Create Own Function In Python

In the below example, we have created str_to_number(str) user defined function. This function takes single argument as a string and return integer, float and string.

We have also used try block to handle exception. Let’s see how to do that.

def str_to_number( inputString ) :
  if ( "." in inputString ) :
    try:
      result = float( inputString )
    except:
      result = inputString  
  elif ( inputString.isdigit() ) :
      result = int( inputString )
  else:
      result = inputString
  return ( result )
  
  
print(str_to_number('hello.0123'))
print(str_to_number('789'))
print(str_to_number('123abc'))
print(str_to_number('#2340Ohasfhas'))
print(str_to_number('12.25'))
print(str_to_number('77.77hello'))

#Output:

hello.0123
789
123abc
#2340Ohasfhas
12.25
77.77hello

06 Python Convert Comma-Separated String Numbers

  1. Using Replace Function
>>> a = '7,000,000'
>>> int(a.replace(',', ''))
7000000
  1. Using Locale Module

The locale is a Python’s module used for internationalization and localization support library. It provides a standard way to handle operations that may depend on the language or location of a user.

import locale
a = '1,000,000'
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
print(locale.atof(a))

#Output: 1000000.0

That’s it for now. We hope this article helped you to learn how to convert string to integer in different ways in python.

Additionally, read our guide:

  1. How to Select Data Between Two Dates in MySQL
  2. Error After php artisan config:cache In Laravel
  3. Specified Key Was Too Long Error In Laravel
  4. AJAX PHP Post Request With Example
  5. How To Use The Laravel Soft Delete
  6. How To Add Laravel Next Prev Pagination
  7. cURL error 60: SSL certificate problem: unable to get local issuer certificate
  8. Difference Between Factory And Seeders In Laravel
  9. Laravel: Increase Quantity If Product Already Exists In Cart
  10. How To Calculate Age From Birthdate
  11. How to Convert Base64 to Image in PHP
  12. Check If A String Contains A Specific Word In PHP
  13. Dynamically Populate A Select Field’s Choices In ACF
  14. How To Find Duplicate Records in Database
  15. Difference between del, remove and pop on lists
  16. How To Downgrade An NPM Package

Please let us know in the comments if everything worked as expected, your issues, or any questions. If you think this article saved your time & money, please do comment, share, like & subscribe. Thank you in advance 🙂. Keep Smiling! Happy Coding!

 
 

Leave a Comment