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.]
Use the String. replace() method to replace double with single quotes, e.g. const replaced = str. replace(/"/g, "'"); . The replace method will return a new string where all occurrences of double quotes are replaced with single quotes.
Method 1 : Using the replace() method To replace a single quote from the string you will pass the two parameters. The first is the string you want to replace and the other is the string you want to place. In our case it is string. replace(” ' “,” “).
As shown above, even though you want to replace a single quote at a time, you need to put double quotes between the double quotes, i.e. to replace a single quote you actually need 4 quotes in a row.
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))
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With