How to parse a string to integer and float in Python 3.8?
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?
Nguyen Truong Giang Jun 17 2021
You can use
int()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!
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.