ThatsOkay
ThatsOkay

Reputation: 523

I want to replace single quotes with double quotes in a list

So I am making a program that takes a text file, breaks it into words, then writes the list to a new text file.

The issue I am having is I need the strings in the list to be with double quotes not single quotes.

For example

I get this ['dog','cat','fish'] when I want this ["dog","cat","fish"]

Here is my code

with open('input.txt') as f:
    file = f.readlines()
nonewline = []
for x in file:
    nonewline.append(x[:-1])
words = []
for x in nonewline:
    words = words + x.split()
textfile = open('output.txt','w')
textfile.write(str(words))

I am new to python and haven't found anything about this. Anyone know how to solve this?

[Edit: I forgot to mention that i was using the output in an arduino project that required the list to have double quotes.]

Upvotes: 52

Views: 171081

Answers (2)

Harvey
Harvey

Reputation: 5821

Most likely you'll want to just replace the single quotes with double quotes in your output by replacing them:

str(words).replace("'", '"')

You could also extend Python's str type and wrap your strings with the new type changing the __repr__() method to use double quotes instead of single. It's better to be simpler and more explicit with the code above, though.

class str2(str):
    def __repr__(self):
        # Allow str.__repr__() to do the hard work, then
        # remove the outer two characters, single quotes,
        # and replace them with double quotes.
        return ''.join(('"', super().__repr__()[1:-1], '"'))

>>> "apple"
'apple'
>>> class str2(str):
...     def __repr__(self):
...         return ''.join(('"', super().__repr__()[1:-1], '"'))
...
>>> str2("apple")
"apple"
>>> str2('apple')
"apple"

Upvotes: 45

falsetru
falsetru

Reputation: 369054

You cannot change how str works for list.

How about using JSON format which use " for strings.

>>> animals = ['dog','cat','fish']
>>> print(str(animals))
['dog', 'cat', 'fish']

>>> import json
>>> print(json.dumps(animals))
["dog", "cat", "fish"]

import json

...

textfile.write(json.dumps(words))

Upvotes: 74

Related Questions