Error String vs string

Any idea why I get this error? the explanation doesn’t make sense to me. its telling me my argument needs to be in string and not ‘String’?

data: “0.9503310322761536”
[ERROR] [1623329724.899464, 1755.905000]: bad callback: <function my_callback at 0x7f4d79241280>
Traceback (most recent call last):
File “/opt/ros/noetic/lib/python3/dist-packages/rospy/topics.py”, line 750, in _invoke_callback
cb(msg)
File “/home/user/catkin_ws/src/turtlebot/scripts/serviceserver.py”,line 21, in my_callback
requestfloat = float(request)
TypeError: float() argument must be a string or a number, not ‘String’

My code is as follows:

Here are some resources that might help you figure it out on your own.

https://docs.python.org/3/library/functions.html?highlight=float#float

http://wiki.ros.org/rosmsg

Hint: Try checking the types of your variables to see if there is a deference between string and String

If you are still stuck, see below for the solution

Solution

The issue is on line 21 when you call float(request). request is the variable that represents message received by your Subscriber. It is of type String as defined in std_msgs.msg (which you imported). To work with the String message effectively, you need to understand how it is structured. In a terminal, run the following

rosmsg show String

This shows the contents of the message type

[std_msgs/String]:
string data

The first line indicates what package it is from (std_msgs). The second line shows the type variable name of the message’s fields. In this case there is a single field of type string named data.

To access a field from a message, use the following syntax:

<message>.<field>

i.e. request.data

To summarize: string is a build in type in Python. On the other hand, String is a message that has a member data of type string

You can remove the (syntax) error by changing line 21 to:

requestfloat = float(request.data)

As a final note: Everything I have detailed is specific to how messages are structured for Publishers and Subscribers. I suspect that you are intending to use a Service instead. I encourage you to review the sections on ROS Service Servers and Clients, paying special attention to how thy differ form Publishers and Subscribers.

1 Like

Hi @r.franklinismail ,

You must get the string itself inside the data attribute of the String object

Example

def callback(msg):
    print(msg.data)

Further reference:
http://docs.ros.org/en/melodic/api/std_msgs/html/msg/String.html

Try to use

requestfloat = float(request.data)
1 Like