0

I've got a series of arrays that I want to use, but they're not formatted correctly for JavaScript. I'm trying to use Python to edit them, since that's what I'm familiar with, and it's not working quite right. My array looks like this:

text = """[["a", "b", "c"]["d, "e", "f"]]"""

text = list(text)

counter = 0
for letter in text:
  if letter == "]":
    text.insert(counter, ",")
  counter += 1

print (''.join(text))

I am trying to make it so that I get a list of all the characters in text, then my for loop goes through and adds a comma after all the ']'s. The join statement should put the list back into a string again.

My code works fine when I take out the for loop, but it doesn't work at all when I add it. I can't see what I'm doing wrong, any ideas?

1
  • Are you missing the " after the d intentionally? Commented Jan 28, 2017 at 14:25

3 Answers 3

3

You must not change a list, you are iterating over. To solve your problem, just use replace:

text = text.replace('][', '], [')
Sign up to request clarification or add additional context in comments.

Comments

1

You could use re.sub:

import re

text = re.sub(r']', r'],', text)

Comments

0

The loop increases the insert position and thus its inserts comma in a text piece shifted after previous iteration not taking into accumulated offset into the account. To fix it you may either iterate from right to the left instead or, alternatively, to add a number of previously inserted commas to the current position. But it's much more simple to use replace:

 `text.replace("]","],")`

I think you don't really need the trailing comma, and commas before ']', so this combination will do the full job:

result = text.replace("]","],").replace(",]","]")[0:-1]

Alternatively, we may use regexps:

import re
brcommare = re.compile(r'(\]+)(?=[^]])')
result = re.sub(brcommare,r'\1,',text)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.