0

I have a string file that looks like this:

["2004" "0" "23" "4.5"]
["2004" "0" "26" "4.8"]
["2004" "0" "16" "3.5"]
["2004" "0" "25" "7.5"]

However at the time that I try to manipulate it, the program gives me an error, this doesn't reads the " (of course), I've been looking for a code that not only eliminates that char but also [ and that keeps my list instead of concatenating it into a whole line. Any ideas?

the final outcome will be exactly the same but without

[" " " " " " "    "]

the code that I'm using is the following:

final= re.sub(r'[^0-9.\s\n], r' ', list)

what this is doing is:

2004 0 23 4.5 2004 0 26 4.8
2
  • Can you give the output you would like to see? I'm not sure I follow from your description. Commented Sep 11, 2014 at 19:09
  • Can't you just run a str.translate and remove "s? Commented Sep 11, 2014 at 19:31

2 Answers 2

1

The naïve answer is just to remove those characters:

myfilecontents = """\
["2004" "0" "23" "4.5"]
["2004" "0" "26" "4.8"]
["2004" "0" "16" "3.5"]
["2004" "0" "25" "7.5"]"""

print(myfilecontents.replace('"', '').replace('[', '').replace(']', ''))
#>>> 2004 0 23 4.5
#>>> 2004 0 26 4.8
#>>> 2004 0 16 3.5
#>>> 2004 0 25 7.5
Sign up to request clarification or add additional context in comments.

2 Comments

thank you this does takes off the undessired chars however by ldoing this my txt file looses its list format. so instead it shows now all the information in just one line instead of breakinbg it up into a list.
@Mel it's likely something else is causing this, as my code doesn't change newlines at all.
0

Indeed there is a lot of ways to solve this problem. Using the combo maktrans + replace + split should be an approach.

from string import maketrans

text = """["2004" "0" "23" "4.5"]
["2004" "0" "26" "4.8"]
["2004" "0" "16" "3.5"]
["2004" "0" "25" "7.5"]"""

parsed = text.translate(maketrans('" ', '#,')).replace('#', '').split('\n')
parsed = [eval(i) for i in parsed]

4 Comments

Thank you Mauro, I tried it, but im still getting the same result all the lines into one same line
Well, do you want to convert it into Python lists, don't? This is what it is doing!
Note that literal_eval is probably a better choice here.
@Veedrac: That depends on what the OP actually wants here. Is he actually looking for a list of strings for each line?

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.