Python – Convert Float to digit list
Sometimes, while working with Python data, we can have a problem in which we need to convert a float number into a list of digits. This problem is common in day-day programming. Let’s discuss certain ways in which this task can be performed.
Method #1: Using builtin methods
Python3
# Python3 code to demonstrate working of# Convert Float to digit list# initialize NN = 6.456# printing Nprint("The floating number is : " + str(N))# Convert Float to digit listx = str(N)res=[]digs="0123456789"for i in x: if i in digs: res.append(int(i))# printing resultprint("List of floating numbers is : " + str(res)) |
The floating number is : 6.456 List of floating numbers is : [6, 4, 5, 6]
Method #2: Using list comprehension + isdigit():
The combination of above functions can be used to perform this task. In this, we first convert the float number to string and then iterate it converting each digit to integer and constructing the list using list comprehension.
Python3
# Python3 code to demonstrate working of# Convert Float to digit list# using list comprehension + isdigit()# initialize NN = 6.456# printing Nprint("The floating number is : " + str(N))# Convert Float to digit list# using list comprehension + isdigit()res = [int(ele) for ele in str(N) if ele.isdigit()]# printing resultprint("List of floating numbers is : " + str(res)) |
The floating number is : 6.456 List of floating numbers is : [6, 4, 5, 6]
Method #3: Using map() + regex expression + findall():
The combination of above functionalities can be used to perform this task. In this, we iterate through list using map() and extract and convert each element of float number using regex expression and findall().
Python3
# Python3 code to demonstrate working of# Convert Float to digit list# using map() + regex expression + findall()import re# initialize NN = 6.456# printing Nprint("The floating number is : " + str(N))# Convert Float to digit list# using map() + regex expression + findall()res = list(map(int, re.findall('\d', str(N)))) # printing resultprint("List of floating numbers is : " + str(res)) |
The floating number is : 6.456 List of floating numbers is : [6, 4, 5, 6]
Method #4: Using str(),replace(),list(),map() methods
Python3
# Python3 code to demonstrate working of# Convert Float to digit list# initialize NN = 6.456# printing Nprint("The floating number is : " + str(N))# Convert Float to digit listx = str(N).replace(".", "")res = list(map(int, x))# printing resultprint("List of floating numbers is : " + str(res)) |
The floating number is : 6.456 List of floating numbers is : [6, 4, 5, 6]





Please Login to comment...