String to Integer and Back Again Python

To convert Python string to int, employ the int() part. The int() is a built-in function that accepts the initial cord and the optional base representing the data as arguments and returns an integer.

str = "1921" print(blazon(str)) print("Afterwards converting Python String to Integer") integer = int(str) impress(integer) print(type(integer))

Output

<class 'str'> Later converting Python Cord to Integer 1921 <class 'int'>

You tin can run across from the output that nosotros take successfully converted a cord to an integer in Python.

Permit's see how to convert dorsum to String from integer.

To store an integer value every bit an int in Python, assign a number to any variable, and it volition become an integer data type. Of course, you can also use the String literal to store an integer.

If you define chiliad = "10," Python understands that you want to shop integer 10 every bit a cord.

Although there are numerous other number systems, such as binary and hexadecimal, which use different bases to represent an integer.

For example, y'all can represent the number 1 hundred and ten(110) in binary and hexadecimal equally 1101110 and 6e, respectively.

Python dissimilar number data types

  1. int (signed integers) − They are frequently chosen just ints or integers, are positive or negative whole numbers with no decimal point.

  2. long (long integers ) − As well chosen longs, they are integers of unlimited size, written like integers and followed by the uppercase or lowercase Fifty.
  3. float (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 as well be in scientific note, with Due east or east indicating the ability of ten (2.5e2 = two.five x x2 = 250).
  4. complex (circuitous numbers) − are of the form a + bJ, where a and b are floats, and J (or j) represents the square root of -1 (which is an imaginary number). The existent part 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 dissimilar information types. For example, two possible Python data types for representing the integer are the post-obit.

  1. Integer
  2. String

Let's represent an integer using a string literal. See the post-obit code.

# app.py  v1 = "1" v2 = "eleven"  print('The value of v1 is: ', v1) print('The data blazon of v1 is:', blazon(v1)) print('The value of v2 is: ', v2) print('The value of v2 is: ', type(v2))        

Output

python3 app.py The value of v1 is:  i The data type of v1 is: <class 'str'> The value of v2 is:  11 The value of v2 is:  <class 'str'>

The Python interpreter understands that yous want to store the integers 1 and 11 every bit strings.

Python str() is a standard inbuilt function to convert the integer to string value.

You phone call it with the String containing the number as the statement, and information technology returns the number converted to an integer.

Convert Python String to Int with different bases

You lot have to proceed in heed many factors and bases while converting from one format to another format. For example, if you accept the decimal integer represented every bit a cord and demand to catechumen the Python cord to an int, y'all laissez passer the String to the int() method, which returns a decimal integer.

If you are looking for a solution to converting Python string to int and int to string, you lot will find your answer in this postal service.

By the end of this tutorial, you'll understand:

  1. How to convert Python string to int.
  2. How to parse Python str to int in a different base of operations.
  3. How to convert Python str to int with commas.

Python defines type conversion functions to catechumen one information type to some other, useful in twenty-four hours-to-day and competitive programming.

Nosotros can use the blazon function to get the data type of whatsoever variable.

See the following case.

# app.py  amp = '123' print(type(amp))  eli = 'The Computer Guy' print(type(eli))  num = 1234 print(type(num))  ser = [1, 2, iv] print(type(ser))  dict = {1: 'Android', 2: 'iOS', 3: 'Symbian'} print(type(dict))

Nosotros have taken the different types of variables and printed them on the Python Console. Run across the following output.

How To Convert Python String to Int

Like the str() inbuilt, Python also offers a handy born, which takes a String object as an statement and returns the corresponding integer object.

If yous want to convert the number represented in a string to int, yous must use the int() function. Come across the following example.

# app.py  amp = '123' print(type(amp))  convertedInt = int(amp) print(blazon(convertedInt)) print(convertedInt)

See the below output.

How To Convert Python String to Int and Int to String

We have converted the String to Integer in Python.

Integers are whole numbers. In other words, they have no fractional component. You tin can utilize two data types to store an integer in Python: int and str.

These types offer flexibility for working with integers in different circumstances.

In this tutorial, you'll acquire how to convert a Python string to an int. You'll likewise learn how to catechumen an int to a string.

And so, this is the same as python string to int.

#app.py  eleven = "11" impress(eleven) # Converting cord to number millie = int(xi) impress(millie)        

See the output.

➜  pyt python3 app.py xi 11 ➜  pyt        

Converting str to int from unlike base

Strings can be transformed into numbers using the int() and float() methods. If your String does non have decimal places, you will probably want to catechumen it to aninteger using the int() method.

If the String you want to convert into int belongs to a different number base other than base 10, you tin specify that base for that conversion.

But one thing you need to keep in mind is that the output integer is always in base ten.

Some other thing you need to remember is that a given base of operations must exist between ii to 32. Run into the following instance.

# app.py  amp = '123' print(blazon(amp))  convertedInt = int(amp) impress(blazon(convertedInt)) print(convertedInt)  convertedInt8 = int(amp, base=viii) print(type(convertedInt)) print(convertedInt)  convertedInt16 = int(amp, base=sixteen) print(type(convertedInt16)) print(convertedInt16)  convertedInt32 = int(amp, base=32) print(type(convertedInt32)) print(convertedInt32)

See the below output.

Converting String to int from different base

While converting from String to int, yous may get a ValueError exception. The ValueError exception occurs if the Cord y'all desire to convert does not represent any numbers.

If y'all're going to catechumen the hexadecimal number to an integer, yous will  non have to pass the statement base=16  in the int()  function.

It will raise the ValueError exception if any digit does non vest to a decimal number organization.

Yous should remember some of the exceptional cases:

  1. As an statement, the floating-point(an integer with a partial part) volition render the float rounded down to the nearest whole integer. For example: print(int(11.21)) will print vii. Also, print(int("11.21")) will result in the Fault since the String is an invalid argument to convert to an integer.

                    Traceback (nigh recent call last):   File "<stdin>", line 1, in <module> ValueError: invalid literal for int() with base x: 'xi.21'              
  2. Also, whatever integer in words, if given as the argument, will return the aforementioned error every bit above: print(int("11")) will provide an error every bit follows.

                    Traceback (most recent call last):   File "<stdin>", line 1, in <module> ValueError: invalid literal for int() with base 10: 'eleven'              

The int() office assumes that the string argument represents the decimal integer by default. If, however, y'all pass the hexadecimal String to int() method, then you lot'll see the ValueError.

Run across the following code.

# app.py  v1 = "0x11E"  impress('The value of v1 is: ', v1) print('The data type of v1 is:', blazon(v1))  conv = int(v1) impress(conv)

Output

python3 app.py The value of v1 is:  0x11E The data type of v1 is: <class 'str'> Traceback (nigh recent call concluding):   File "app.py", line 6, in <module>     conv = int(v1) ValueError: invalid literal for int() with base 10: '0x11E'

The fault message suggests that the String is not a valid decimal integer.

It's essential to recognize the difference betwixt two types of failed results of passing the String to int():

  1. 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).
  2. Logical Error: The int() office does know how to parse a String, merely not the way you expected.

Parse int to string in Python

We can use the inbuilt str() part to parse Python int to String to convert an integer to Cord.

Parsing is the same every bit converting in programming.

Run into the following example.

# app.py  hexValue = 0x2f22 print(hexValue) print(type(hexValue)) hexValue = str(hexValue) print(hexValue) print(type(hexValue))

See the output below.

Convert Python Int to String Tutorial

Meet another instance of Int to String conversion in Python.

# app.py  digit = 1921 print(digit) print(type(digit)) digit = str(digit) impress(digit) print(type(digit))

Convert Python Int to String Tutorial Example

Python cord to float

To convert a cord to float in Python, use the bladder() role. The float() 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.

Run into the following example for a demonstration.

# app.py  eleven = '11.21' hopper = 19.21  el = float(eleven) + hopper print ("The value of el = ",el)        

See the following output.

➜ pyt python3 app.py The value of el = xxx.42 ➜ pyt        

For more information, check out converting String to Float 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 mode to catechumen those strings into an int is to apply a listing comprehension. As shown in the instance beneath, a  new list will be created to utilise 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 [11, nineteen, 21] ➜  pyt        

Converting String to int with commas

What about cord numbers with commas like "xi,000,000". If you endeavour to catechumen 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 tin can use the U.s.a. locale setting like the following.

locale.setlocale( locale.LC_ALL, "en_US.UTF-8")        

However, this may cause problems with different locations.

So, one other solution is to supplant the comma with zippo. For instance, see the lawmaking below.

# app.py  elevenmillion = '11,000,000' 11 = int(elevenmillion.replace(',',''))  print ("The integer value", 11)        

See the following output.

➜  pyt python3 app.py The integer value 11000000 ➜  pyt        

Python int to String

To convert Python integer to cord, use the built-in str() function. The str() is a congenital-in Python function that takes whatever data type and converts it into a string, including integers, and returns a string.

See the post-obit code.

# app.py  v1 = 1 v2 = 11  print('The value of v1 is: ', v1) print('The data type of v1 is:', type(v1)) print('The value of v2 is: ', v2) print('The value of v2 is: ', type(v2))        

Output

python3 app.py The value of v1 is:  1 The data blazon of v1 is: <class 'int'> The value of v2 is:  eleven The value of v2 is:  <class 'int'>

If you want to get the data type of any value, use the blazon() role.

Conclusion

Strings tin be converted to numbers using theint() and float() functions. If the String does not have decimal places, convert it to aninteger using theint() method. The str() function is used to convert the integer to Cord.

The ord() role converts the graphic symbol to an integer.

The hex() office converts an integer to a hexadecimal string.

The oct() role converts an integer to the octal String.

That is it for the tutorial.

Recommended Posts

Python bladder()

Python Cord to Listing

Python information types

martinezalackeen.blogspot.com

Source: https://appdividend.com/2022/03/20/python-string-to-int/

0 Response to "String to Integer and Back Again Python"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel