Mike Thunder
Mike Thunder

Reputation: 449

Convert string to int in a list by removing floating (Python)

I have a list like this:

List= [("Mike,"Admin","26,872"),
       ("John,"Admin","32,872"),
       ("Mark,"Admin","26,232")...]

what I want to achieve is the following:

List= [("Mike,"Admin", 26872),
       ("John,"Admin", 32872),
       ("Mark,"Admin", 26232)...]

so for the every third element I want to remove comma and convert it to int. I tried for example to do replace but the list doesn't support replace method.

Just a test:

    accounts = sorted(List, key=lambda account: account[2], reverse=True)
    for i,j,k in accounts:
         k.replace(",", "")
         int k

Any ideas?

Upvotes: 0

Views: 91

Answers (1)

Maroun
Maroun

Reputation: 95968

One way would be:

[(a, b, c.replace(",", "")) for a, b, c in List]

This will create a new list having the first two values unchanged, and the third with the comma being removed.

If you want to have the third value as an int, you can simply.. cast it.

Note that you can iterate on the list in a different way,

[(w[0], w[1], w[2]) for w in List]

Upvotes: 1

Related Questions