Pieter
Pieter

Reputation: 151

Converting list of strings to floats and add 1

I have parsed my input to this list:

lst = ['6,3', '3,2', '9,6', '4,3']

How to change this list of strings to a list of floats? While the numbers that are nw strings are not seperated by a . but by a ,

After that i would like to add 1 to every float. So that the ouput becomes:

lst = [7.3, 4.2, 10.6, 5.4]

Upvotes: 2

Views: 120

Answers (3)

Ffisegydd
Ffisegydd

Reputation: 53678

You could use locale.atof(string) which is a function designed to convert a string to a float, taking into account the locale settings, i.e. taking into account that in some cultures/languages the comma is used to make the decimal point, as opposed to a period.

The list comprehension for this would then be something like this

from locale import atof

a = ['6,3', '3,2', '9,6', '4,3']
b = [atof(i) + 1 for i in a]

Unfortunately, I cannot test that it works with a comma as my locale is set to use a period.

If you don't want to use locale.atof then the code below will do a similar job by converting the comma to a period. You can replace the comma with a period using str.replace.

a = ['6,3', '3,2', '9,6', '4,3']
b = [float(i.replace(',', '.')) + 1 for i in a]
# [7.3, 4.2, 10.6, 5.3]

This list comprehension is equivalent to

a = ['6,3', '3,2', '9,6', '4,3']
b = []
for i in a:
    j = float(i.replace(',', '.')) + 1
    b.append(j)

Upvotes: 5

101
101

Reputation: 8989

Using list comprehension:

lst = ['6,3', '3,2', '9,6', '4,3']
new_lst = [float(num.replace(',','.')) + 1 for num in lst]

Upvotes: 1

Łukasz Rogalski
Łukasz Rogalski

Reputation: 23203

What about:

l2 = [float(num.replace(',', '.')) + 1 for num in lst]

First you replace comma by dot in string, after that you cast to float and add 1 to result. Operation is perfomed for each element in list.

Upvotes: 3

Related Questions