0

I've been searching around for a while and not found the solution. Any help is very much appreciated!

Problem: I'd like to find and replace all percentage symbols ("%") in a multiple row list. The below example is a short version of my actual data which has many more rows and columns. Here's the example:

x = [['name', 'col1', 'col2'],
['a', '43.63%', '2'],
['b', '14.20%', '3.5%'],
['c', '10%', '3.4%']]

Desired outcome:

x = [['name', 'col1', 'col2'],
['a', '43.63', '2'],
['b', '14.20', '3.5'],
['c', '10', '3.4']]

My code:

for row in x:
    for item in row:
        item = item.replace("%", "")
print x

I thought this would replace each item with the new string; however, when I now print x I get the original list with "%". Please could anyone see where I'm going wrong? Thanks in advance!

0

1 Answer 1

2

You need to actually replace the item in the list.

Strings are immutable so you're creating a new item and basically not doing anything with it here:

# create wanted string, but where should it go?
item = item.replace("%", "")

You can use enumerate for doing what you want:

for row in x:
    for index, item in enumerate(row):
        # create string *and update row*
        row[index] = item.replace("%", "")
print x
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.