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!
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)
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.
New accounts only. By submitting your email you agree to our Privacy Policy
Scale up as you grow — whether you're running one virtual machine or ten thousand.
Sign up and get $200 in credit for your first 60 days with DigitalOcean.*
*This promotional offer applies to new accounts only.