Jose Rodriguez
Jose Rodriguez

Reputation: 101

Removing all commas from list in Python

My issue: I'd like to add all the digits in this string '1.14,2.14,3.14,4.14' but the commas are causing my sum function to not work correctly.
I figured using a strip function would solve my issue but it seems as though there is still something I'm missing or not quite understanding.

total = 0
for c in '1.14,2.14,3.14'.strip(","):
    total = total + float(c)
print total

I have searched how to remove commas from a string but I only found information on how to remove commas from the beginning or ending of a string.

Additional Info: Python 2.7

Upvotes: 4

Views: 89219

Answers (8)

Pooja12
Pooja12

Reputation: 41

Remove commas from list

Updated for Python3:

a = [1,2,3,4,5]
b = ''.join(str(a).split(','))

removes commas from list i.e.

[1,2,3,4,5]  --> [1 2 3 4 5]

Upvotes: 4

Shreyas Dangare
Shreyas Dangare

Reputation: 31

Use this to remove commas and white spaces

a = [1,2,3,4,5]
print(*a, sep = "")

Output:- 12345

Upvotes: 3

Fasih Khan
Fasih Khan

Reputation: 11

values=input()         
l=values.split(",")   
print(l)

With values=1,2,3,4,5

the result is ['1','2','3','4','5']

Upvotes: 1

pradyunsg
pradyunsg

Reputation: 19406

You need split not strip.

>>> for c in '1,2,3,4,5,6,7,8,9'.split(","):
    print float(c)

1.0
2.0
3.0
4.0
5.0
6.0
7.0
8.0
9.0

Or if you want a list comprehension:

>>> [float(c) for c in '1,2,3,4,5,6,7,8,9'.split(",")]
[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]

And for getting the sum,

>>> sum(map(float, '1,2,3,4,5,6,7,8,9'.split(",")))
45.0

Upvotes: 1

Nadir Sampaoli
Nadir Sampaoli

Reputation: 5555

Since there seem to be a pattern in your input list of floats, this one-liner generates it:

>>> sum(map(float, ','.join(map(lambda x:str(x+0.14), range(1,5))).split(',')))
10.559999999999999

And since it doesn't make much sense joining with commas and immediately splitting by commas, here's a little saner piece of code:

>>> sum(map(float, map(lambda x:str(x+0.14), range(1,5))))
10.559999999999999



And if you actually meant you wanted to sum single digits and not the actual floating-point numbers (although I doubt it since you cast to float in your sample code):

>>> sum(map(int, ''.join(map(lambda x:str(x+0.14), range(1,5))).replace('.', '')))
30

Upvotes: 0

Robᵩ
Robᵩ

Reputation: 168626

This will add all of the digits in the first string in your question:

sum(float(x) for x in '1.14,2.14,3.14,4.14' if x.isdigit())

Upvotes: 0

alestanis
alestanis

Reputation: 21863

You don't want strip, you want split.

The split function will separate your string into an array, using the separator character you pass to it, in your case split(',').

Upvotes: 4

Dan Lecocq
Dan Lecocq

Reputation: 3483

I would use the following:

# Get an array of numbers
numbers = map(float, '1,2,3,4'.split(','))

# Now get the sum
total = sum(numbers)

Upvotes: 9

Related Questions