Question

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

ex.[‘march 5’,430.0]


Submit an answer


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!

Sign In or Sign Up to Answer

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.

KFSys
Site Moderator
Site Moderator badge
May 3, 2023

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)

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel