How To Change A String To An Int In Python
To store an integer value as an int in Python, assign a number to any variable, and it will get an integer data type. Of course, you can besides use the String literal to shop an integer.
If you define k = "10," Python understands that you desire to store integer 10 as a cord.
Although there are numerous other number systems, such equally binary and hexadecimal, which use different bases to stand for an integer.
For instance, y'all tin can correspond the number one hundred and ten(110) in binary and hexadecimal as 1101110 and 6e, respectively.
Now, let'due south come across how to convert a string to an integer data type.
Python string to int
To catechumen a string to int in Python, utilise the int() part. The int() is a built-in function that accepts the initial Cord and the optional base representing the information as arguments and returns an integer.
str = "1921" impress(blazon(str)) print("After converting Python String to Integer") integer = int(str) print(integer) print(type(integer))
Output
<class 'str'> Later converting Python String to Integer 1921 <class 'int'>
You tin see from the output that nosotros have successfully converted a cord to an integer in Python.
Let's come across how to catechumen back to String from integer.
Python different number information types
-
int (signed integers) − They are often called simply ints or integers, are positive or negative whole numbers with no decimal point.
- long (long integers ) − Also called longs, they are integers of unlimited size, written similar integers and followed by the majuscule or lowercase L.
- bladder (floating point real values) − Also called floats, correspond real numbers and are written with the decimal point dividing the integer and fractional parts. Floats may besides be in scientific notation, with E or due east indicating the power of ten (2.5e2 = 2.v x xtwo = 250).
-
complex (complex numbers) − are of the class a + bJ, where a and b are floats, and J (or j) represents the foursquare root of -ane (which is an imaginary number). The existent role of the number is a, and the imaginary part is b. Circuitous numbers are non used much in Python programming.
Representing Integers in Python
An integer can be stored using different data types. For example, two possible Python data types for representing the integer are the following.
- Integer
- String
Allow's stand for an integer using a string literal. See the following code.
# app.py v1 = "1" v2 = "eleven" print('The value of v1 is: ', v1) print('The information type of v1 is:', blazon(v1)) print('The value of v2 is: ', v2) print('The value of v2 is: ', blazon(v2))
Output
python3 app.py The value of v1 is: 1 The data type of v1 is: <class 'str'> The value of v2 is: 11 The value of v2 is: <course 'str'>
The Python interpreter understands that you want to store the integers 1 and eleven as strings.
Python str() is a standard inbuilt part to convert the integer to string value.
You call it with the Cord containing the number every bit the argument, and it returns the number converted to an integer.
Convert Python String to Int with different bases
Y'all accept to go along in listen many factors and bases while converting from 1 format to some other format. For case, if you have the decimal integer represented as a string and need to convert the Python string to an int, y'all pass the String to the int() method, which returns a decimal integer.
If y'all are looking for a solution to converting Python string to int and int to cord, yous will find your answer in this post.
By the end of this tutorial, yous'll understand:
- How to convert Python string to int.
- How to parse Python str to int in a different base.
- How to convert Python str to int with commas.
Python defines type conversion functions to convert one information type to another, useful in day-to-twenty-four hour period and competitive programming.
We tin use the type function to become the data type of any variable.
See the following instance.
# app.py amp = '123' print(type(amp)) eli = 'The Computer Guy' print(type(eli)) num = 1234 impress(blazon(num)) ser = [i, 2, 4] print(type(ser)) dict = {1: 'Android', 2: 'iOS', 3: 'Symbian'} print(type(dict))
Nosotros accept taken the different types of variables and printed them on the Python Console. See the following output.
Like the str() inbuilt, Python also offers a handy built-in, which takes a String object every bit an argument and returns the corresponding integer object.
If you want to catechumen the number represented in a string to int, y'all must utilize the int() function. See the following example.
# app.py amp = '123' print(type(amp)) convertedInt = int(amp) print(type(convertedInt)) print(convertedInt)
Meet the below output.
We take converted the Cord to Integer in Python.
Integers are whole numbers. In other words, they have no fractional component. You lot can use two data types to shop an integer in Python: int and str.
These types offer flexibility for working with integers in unlike circumstances.
In this tutorial, you'll acquire how to convert a Python string to an int. You'll too larn how to convert an int to a string.
And so, this is the same equally python string to int.
#app.py 11 = "11" print(eleven) # Converting cord to number millie = int(eleven) print(millie)
See the output.
➜ pyt python3 app.py eleven 11 ➜ pyt
Converting str to int from dissimilar base
Strings tin exist transformed into numbers using the int() and float() methods. If your String does not accept decimal places, you will probably desire to convert it to aninteger using the int() method.
If the String you lot want to catechumen into int belongs to a different number base other than base 10, y'all tin can specify that base for that conversion.
But one thing y'all need to go along in mind is that the output integer is e'er in base 10.
Another affair you need to remember is that a given base must be between 2 to 32. Run across the following example.
# app.py amp = '123' impress(type(amp)) convertedInt = int(amp) print(type(convertedInt)) print(convertedInt) convertedInt8 = int(amp, base of operations=8) print(type(convertedInt)) print(convertedInt) convertedInt16 = int(amp, base=16) impress(type(convertedInt16)) print(convertedInt16) convertedInt32 = int(amp, base=32) print(type(convertedInt32)) print(convertedInt32)
Come across the below output.
While converting from String to int, y'all may get a ValueError exception. The ValueError exception occurs if the String you want to convert does not represent any numbers.
If you're going to convert the hexadecimal number to an integer, you will not take to pass the argument base of operations=sixteen in the int() function.
It will heighten the ValueError exception if any digit does not vest to a decimal number system.
You should call up some of the exceptional cases:
-
Equally an argument, the floating-indicate(an integer with a fractional part) volition return the float rounded downwards to the nearest whole integer. For case: print(int(11.21)) will print vii. Also, print(int("eleven.21")) volition result in the Error since the String is an invalid statement to catechumen to an integer.
Traceback (most contempo call final): File "<stdin>", line 1, in <module> ValueError: invalid literal for int() with base 10: '11.21'
-
Besides, any integer in words, if given as the argument, will return the same error as above: print(int("eleven")) will provide an mistake equally follows.
Traceback (most contempo call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for int() with base 10: '11'
The int() function assumes that the string argument represents the decimal integer by default. If, however, you lot pass the hexadecimal Cord to int() method, then you'll see the ValueError.
See the following code.
# app.py v1 = "0x11E" print('The value of v1 is: ', v1) print('The information type of v1 is:', blazon(v1)) conv = int(v1) print(conv)
Output
python3 app.py The value of v1 is: 0x11E The data blazon of v1 is: <class 'str'> Traceback (most contempo call concluding): File "app.py", line half-dozen, in <module> conv = int(v1) ValueError: invalid literal for int() with base ten: '0x11E'
The error message suggests that the String is not a valid decimal integer.
It's essential to recognize the difference betwixt 2 types of failed results of passing the String to int():
- Syntax Error: A ValueError will be thrown when theint() function doesn't know how to parse the String using a provided base (10 by default).
- Logical Error: The int() function does know how to parse a String, but not the mode you expected.
Parse int to string in Python
Nosotros tin can use the inbuilt str() function to parse Python int to Cord to convert an integer to String.
Parsing is the same as converting in programming.
See the following example.
# app.py hexValue = 0x2f22 print(hexValue) impress(type(hexValue)) hexValue = str(hexValue) print(hexValue) print(type(hexValue))
Meet the output below.
See another example of Int to Cord conversion in Python.
# app.py digit = 1921 print(digit) impress(blazon(digit)) digit = str(digit) print(digit) print(type(digit))
Python string to float
To convert a string to float in Python, utilise the float() part. The bladder() is a congenital-in Python method that coerces the string value to an integer. You may use a floating class for converting the decimal String to a float number.
See the following example for a demonstration.
# app.py eleven = '11.21' hopper = xix.21 el = float(xi) + hopper print ("The value of el = ",el)
Come across the post-obit output.
➜ pyt python3 app.py The value of el = 30.42 ➜ pyt
For more data, check out converting String to Bladder in Python example.
Converting cord numbers in a list to integers
If you intend to convert the string numbers in the Python list, then 1 way to convert those strings into an int is to use a list comprehension. Equally shown in the instance below, a new list will be created to use the int in each iteration.
# app.py str_list = ['11', 'xix', '21'] int_list = [int(a) for a in str_list] print (int_list)
See the following output.
➜ pyt python3 app.py [xi, 19, 21] ➜ pyt
Converting Cord to int with commas
What most string numbers with commas similar "11,000,000". If you lot try to convert this Cord using an int or float, information technology will generate the Error because of the commas.
The solution to the above Error is by importing the locale.
import locale
Now, you can utilize the USA locale setting similar the following.
locale.setlocale( locale.LC_ALL, "en_US.UTF-8")
However, this may crusade problems with unlike locations.
And then, i other solution is to replace the comma with nothing. For example, see the code below.
# app.py elevenmillion = '11,000,000' eleven = int(elevenmillion.replace(',','')) impress ("The integer value", 11)
Run into the following output.
➜ pyt python3 app.py The integer value 11000000 ➜ pyt
Python int to String
To convert Python integer to string, use the congenital-in str() function. The str() is a built-in Python function that takes any information blazon and converts it into a string, including integers, and returns a string.
Encounter the following lawmaking.
# app.py v1 = 1 v2 = xi print('The value of v1 is: ', v1) print('The data blazon of v1 is:', blazon(v1)) print('The value of v2 is: ', v2) impress('The value of v2 is: ', type(v2))
Output
python3 app.py The value of v1 is: ane The data type of v1 is: <class 'int'> The value of v2 is: 11 The value of v2 is: <course 'int'>
If yous want to become the data type of any value, apply the blazon() function.
Determination
Strings can be converted to numbers using theint() and float() functions. If the String does non take decimal places, convert information technology to aninteger using theint() method. The str() part is used to convert the integer to String.
The ord() office converts the character to an integer.
The hex() function converts an integer to a hexadecimal cord.
The oct() function converts an integer to the octal String.
That is information technology for the tutorial.
Recommended Posts
Python float()
Python Cord to Listing
Python data types
Source: https://appdividend.com/2022/01/22/python-string-to-int/
Posted by: schoenbergcontly.blogspot.com
0 Response to "How To Change A String To An Int In Python"
Post a Comment