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.
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.
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
- Using Replace Function
>>> a = '7,000,000' >>> int(a.replace(',', '')) 7000000
- 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:
- How to Select Data Between Two Dates in MySQL
- Error After php artisan config:cache In Laravel
- Specified Key Was Too Long Error In Laravel
- AJAX PHP Post Request With Example
- How To Use The Laravel Soft Delete
- How To Add Laravel Next Prev Pagination
- cURL error 60: SSL certificate problem: unable to get local issuer certificate
- Difference Between Factory And Seeders In Laravel
- Laravel: Increase Quantity If Product Already Exists In Cart
- How To Calculate Age From Birthdate
- How to Convert Base64 to Image in PHP
- Check If A String Contains A Specific Word In PHP
- Dynamically Populate A Select Field’s Choices In ACF
- How To Find Duplicate Records in Database
- Difference between del, remove and pop on lists
- 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!