How to parse a string to integer and float in Python 3.8?
Dung Do Tien
Jun 17 2021
175
Hello everybody, I just studying Python 3.8 and I have a string number, how can I convert it to int, float data type?
- "2" -> 2(int)
- "5.234" -> 5.234 (float)
- "5.234" -> 5 (int)
Please help me, how can I convert them?
Have 2 answer(s) found.
-
N0
Nguyen Truong Giang Jun 17 2021
You can use
float()
andint()
to help convert them. For example:>>> a = "2" >>> b = "5.234" >>> int(a) 2 >>> float(b) 5.234 >>> int(float(b)) 545 >>> int(b) 545
Hope it helpful for you!
-
X0
Xhana Ahmetaj Jun 17 2021
You can create a common function help convert string to int or float as below:
def num(a): try: return int(a) except ValueError: return float(a)
I still use it in my project. And it work fine for me.
* Type maximum 2000 characters.
* All comments have to wait approved before display.
* Please polite comment and respect questions and answers of others.