Report this

What is the reason for this report?

how to convert a string into a float ex.['march 5',430.0]

Posted on May 3, 2023
Ryan

By Ryan

ex.[‘march 5’,430.0]



This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Heya,

From what you have provided as an example. it seems like you want to convert a list containing a string and a float into a new list, where the string is replaced with a float.

In the exact example you provided it seems that the string represents a date, but it’s not clear how you want to convert the date string into a float. I will assume that you want to convert the date string into a timestamp (float) for this explanation. You can use the datetime module in Python. Here’s an example of how to do it:

from datetime import datetime

def convert_string_to_timestamp(date_str, date_format):
    dt = datetime.strptime(date_str, date_format)
    timestamp = dt.timestamp()
    return timestamp

def convert_list_to_floats(input_list, date_format="%B %d"):
    output_list = []
    for item in input_list:
        if isinstance(item, str):
            output_list.append(convert_string_to_timestamp(item, date_format))
        elif isinstance(item, (int, float)):
            output_list.append(float(item))
    return output_list

# Example usage:
input_list = ['March 5', 430.0]
output_list = convert_list_to_floats(input_list)
print(output_list)

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.