Convert string to int Python is different from other programming languages like Java, c and etc. Python doesn’t implicitly typecast strings to Integer(numbers).
Python has standard built-in int()
and functionfloat( )
is to convert a string into an integer or float value. Call it with a string containing a number as the argument, and it returns the number converted to an integer:
Convert string to int Python Example
Use Python standard built-in function int() convert string to an integer.
age = "21" print(type(age)) age_number = int(age) print(type(age_number))
Output: <class ‘str’>
<class ‘int’>
string to float Example
Same as int() function, use Python standard built-in function int() convert string to float.
age = "21" print(type(age)) age_number = float(age) print(type(age_number))
Output: <class ‘str’>
<class ‘float’>
QA: What if string content converts into an integer?
It will throw an error. Let’s check the example, for the same. Only change digit to the word in age variables.
age = "one" print(type(age)) age_number = float(age) print(type(age_number))
Output: <class ‘str’>
.....
ValueError: could not convert string to float: 'one'
For more information Official documentation for int()
– https://docs.python.org/3.6/library/functions.html#int
Note : This example (Project) is developed in PyCharm 2018.2 (Community Edition)
JRE: 1.8.0
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.13.6Python 3.7
All Examples of Convert string to int are in Python 3, so it may change its different from python 2 or upgraded versions.