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, and then writes the list to a new text file.

The problem I am facing is that I need the lines in the list with double quotes, not single quotes.

for instance

I get it ['dog','cat','fish']when I need 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. Does anyone know how to solve this?

[Edit: I forgot to mention that I used the output in the arduino project, which required the list to have double quotes.]

+4
source share
4 answers

str list.

JSON, " .

>>> 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))
+8

Python . . :

2.4.1.

... : (') ("). ( ). () , , , , ...

", , - , ". - , .

+1

, , :

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

You can also extend the Python type strand wrap your strings with a new type by changing the method __repr__()to use double quotes instead of single quotes. It is better to be simpler and more explicit using the code above.

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"
+1
source

If you want to add double quotes to the beginning, as well as strings, do this:

words = ['"'+word+'"' for word in words]

Your list will be like this:

['"dog"', '"cat"', '"fish"']
0
source

Source: https://habr.com/ru/post/1669493/


All Articles