49

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.]

ThatsOkay
  • 493
  • 1
  • 4
  • 6
  • ['dog','cat','fish'] is the same as [dog,cat,fish] the quotes are just to sinalize the string. The quotes are not part of the string. Try print(words[0]) and you will understand – Leonardo Hermoso Feb 12 '17 at 02:09
  • 6
    "The issue I am having is I need the strings in the list to be with double quotes not single quotes." - why? What are you going to do with this file that requires double quotes? Are you trying to output JSON or something? (If so, there's a [module](https://docs.python.org/3/library/json.html) for that.) – user2357112 Feb 12 '17 at 02:10
  • Please show the input file. – merlin2011 Feb 12 '17 at 02:12

3 Answers3

69

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))
falsetru
  • 357,413
  • 63
  • 732
  • 636
  • 2
    `json.dumps('dog')` ouputs `'"dog"'` to the file but I want `"dog"`. How to do that? – CKM Apr 27 '17 at 13:14
  • @chandresh, print it. surrounding single quotes are there to represent the object is string. (That's how the `repr` represent). If you print it (or write it to file, ...), you will get what you want. – falsetru Apr 27 '17 at 13:28
  • @falsetru I did that and only after that I posted my comment above. Can you check once again? – CKM Apr 28 '17 at 05:45
  • @chandresh, could you post a separate question and let me know the url of the question. It's hard to know what's the problem without reproducible code. – falsetru Apr 28 '17 at 09:47
  • @falsetru [here](http://stackoverflow.com/questions/43677524/replace-single-quoted-sting-to-double-quoted-string-in-python) – mkrieger1 Apr 28 '17 at 10:20
  • @falsetru I'm not the author of that question, I just commented on it earlier, found that it linked to here and saw your comment. (But it's been closed now anyway) – mkrieger1 Apr 28 '17 at 12:31
  • @mkrieger1, Ah. Sorry, I should mention the chandresh, not you. my apologies. – falsetru Apr 28 '17 at 12:34
  • @chandresh, Your new question post does not involve reproducible code. Please post with code that can reproduce your problem. – falsetru Apr 28 '17 at 12:34
41

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"
Harvey
  • 5,703
  • 1
  • 32
  • 41
-3

In Python, double quote and single quote are the same. There's no different between them. And there's no point to replace a single quote with a double quote and vice versa:

2.4.1. String and Bytes literals

...In plain English: Both types of literals can be enclosed in matching single quotes (') or double quotes ("). They can also be enclosed in matching groups of three single or double quotes (these are generally referred to as triple-quoted strings). The backslash () character is used to escape characters that otherwise have a special meaning, such as newline, backslash itself, or the quote character...

"The issue I am having is I need the strings in the list to be with double quotes not single quotes." - Then you need to make your program accept single quotes, not trying to replace single quotes with double quotes.

Community
  • 1
  • 1
Huy Vo
  • 2,418
  • 6
  • 22
  • 43
  • 12
    This is incorrect. Although Python doesn't distinguish, PostgreSQL for example, does. Passing single quote string column names returns an error if they were defined as double quote column names. It is therefore still necessary to replace the quotes sometimes. – herman Mar 06 '20 at 10:43