1

I can't come up with idea how to get rid of quotes that come with every string in my list of tuples. Tried different approaches from internet, still nothing works for me. Could somebody please help me?

This is my exaple:

[('Alabama', 'Montgomery', '32.361538', '-86.279118'),
 ('Alaska', 'Juneau', '58.301935', '-134.41974')]

I need:

[(Alabama, Montgomery, 32.361538, -86.279118),
 (Alaska, Juneau, 58.301935, -134.41974)]

May be what I need is just to read a file in different way:

My raw data, separated with tab:

Alabama Montgomery  32.361538   -86.279118
Alaska  Juneau  58.301935   -134.41974

I read file with this command:

with open('city-data.txt') as f:
    mylist = [tuple(i.strip().split('\t')) for i in f]
1
  • 1
    You can't if you use repr(..) (or str(..) on lists/tuples), since a repr basically aims to produce an expression, that will generate the object in represents again. You can construct a string where the quotes are removed, but only for printing purposes. Commented Feb 12, 2018 at 18:27

2 Answers 2

1

You can create a class and override its __repr__ method to fit your formatting needs, as follows:

inList = [('Alabama', 'Montgomery', '32.361538', '-86.279118'), ('Alaska', 'Juneau', '58.301935', '-134.41974')]

class Formatter:

    def __init__(self, word):
        self.word = word

    def __repr__(self):
        return self.word


outList = [tuple(Formatter(elem) for elem in tup) for tup in inList]
print(outList)

Output:

[(Alabama, Montgomery, 32.361538, -86.279118), (Alaska, Juneau, 58.301935, -134.41974)]
Sign up to request clarification or add additional context in comments.

Comments

0

If you mean you want that as a python object, that's impossible – the bareword Alabama doesn't mean anything in python unless it's a symbol bound to a value, which is clearly not what you're going for here. You could convert the numeric strings to numbers, though, and end up with

[('Alabama', 'Montgomery', 32.361538, -86.279118),
 ('Alaska', 'Juneau', 58.301935, -134.41974)]

However, I think you probably just want to print the value without quotes, which is simpler:

out = '['
for tup in your_list:
  out += '({},{},{},{}),\n'.format(*tup)
if your_list:
  out = out[:-2]
out += ']'

print out
# [(Alabama,Montgomery,32.361538,-86.279118),                                                                                                      
# (Alaska,Juneau,58.301935,-134.41974)] 

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.