chevron_left

Problem:

Hi there! I am new to the world of Python, and I am just trying new things in programming.
I learned somewhere about the split() method and tried the following program:

number = 43.42
another = number.split()
print(another)

When I executed this program, it generated the following error:

Traceback (most recent call last):                                                                                            
  File "main.py", line 2, in <module>                                                                                         
    another = number.split()                                                                                                  
AttributeError: 'float' object has no attribute 'split'  

All I wanted to do is separating the numbers before and after the decimal point. I have no idea what caused this error. Can anyone here help me solve the problem, please?

Solution:

Hi! As you are a beginner, these errors may demotivate you for now, but you will always encounter such errors, throughout your career as a programmer.

The problem in your program is that you are using a function, that is built for string objects, on float objects. This is what caused the error here. You cannot use a function written for a string object with a float object and vice versa. If you had searched the Internet, you would have found the use of the split() function.

math.modf():
To separate the integer and decimal parts of a floating-point number, Python provides the math.modf() method. The syntax for using this method is as follows:

math.modf(floating_point_number)

This function returns a tuple containing the integer and decimal parts of a number. Following is the example that shows how to use this function:

import math
number = 43.42
separate = math.modf(number)
print(separate)

Output:

(0.4200000000000017, 43.0)  

Note: This method requires floating-point numbers only. If you pass any other type of data, it will throw exceptions.

More Posts

How to solve attributeerror: 'series' object has no attribute 'split'? Alecxe01 - Nov 7
Python attributeerror: 'module' object has no attribute amna - May 24
Attributeerror: 'tensor' object has no attribute '_keras_history'. Alecxe01 - Oct 28
Attributeerror: 'list' object has no attribute 'keys' Naymul01 - Oct 23
Attributeerror: 'str' object has no attribute 'sort' Naymul01 - Oct 19
Series' object has no attribute 'split' Naymul01 - Oct 21
Series' object has no attribute 'split' sam_dev - Sep 21
‘Float’ object cannot be interpreted as an integer. Farkhanda Athar - Jul 11, 2020
Python split string into fixed length substrings Hafsa_Rao - Aug 24
Attributeerror: module 'tensorflow' has no attribute 'session'. Alecxe01 - Nov 2