-1

This is just one line of a file that reads a list of numbers.

I need to remove the commas in the numbers. These numbers are already strings. I am having trouble figuring out how to write this.

['0', '0', '0', '0', '1,799', '']

how would i change 1,799 to 1799

i tried this

        for i in str(doses):
            if "," in i:
                i.replace(",", "")

but it didn't do anything

plz help me understand what i did wrong.

doodlebob
  • 15
  • 1
  • 3
    `replace()` does not change the original string, it makes a new one, so you need to do something with the new string like `new_string = old_string.replace(',', '')` A typical way to do this would be to make a new list: `[s.replace(',', '') for s in some_list]` – Mark Jun 04 '22 at 00:11
  • 1
    There's no need for the `if`. If the string doesn't contain `,`, `replace()` will just return it unchanged. – Barmar Jun 04 '22 at 00:13
  • try this : `doses_beta = [ item.replace(',', '') for item in doses ]` – Jupri Jun 04 '22 at 00:46

3 Answers3

0

To modify the array value in place, you have to re-assign it. The below function illustrates how to do so.

def remove_commas(array):
    for i in range(len(array)):
        if ',' in array[i]:
            array[i] = array[i].replace(',', '')
    return array

Testing:

print(remove_commas(["0","0","0","0","1","1,799",""]))

Output:

['0', '0', '0', '0', '1', '1799', '']
ankitbatra22
  • 417
  • 2
  • 5
0

replace() does not change the value, that returns the value with the character modified, so you must assign the return value to the element that you want apply the replace.

doses = ['0', '0', '0', '0', '1,799', '']
for i in range(len(doses)):
    if ',' in doses[i]:
        doses[i] = doses[i].replace(',', '')
Paul Dlc
  • 133
  • 1
  • 6
0

Try this:

original_list = ['0', '0', '0', '0', '1,799']
resulting_list = [s.replace(',', '') for s in original_list]

print(original_list)
print(resulting_list)

Output: ['0', '0', '0', '0', '1,799'] and ['0', '0', '0', '0', '1799']