Convert single quotes to double quotes python

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

asked Feb 12, 2017 at 2:06

ThatsOkayThatsOkay

4031 gold badge4 silver badges6 bronze badges

3

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

answered Feb 12, 2017 at 2:12

falsetrufalsetru

343k57 gold badges684 silver badges607 bronze badges

8

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"

answered Feb 12, 2017 at 2:28

HarveyHarvey

5,5131 gold badge31 silver badges39 bronze badges

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.

answered Feb 12, 2017 at 2:13

Convert single quotes to double quotes python

Huy VoHuy Vo

2,3366 gold badges26 silver badges43 bronze badges

1

In Python, a string (str) is created by enclosing text in single quotes ', double quotes ", and triple quotes (''', """). It is also possible to convert objects of other types to strings with str().

  • Built-in Types - Text Sequence Type — str — Python 3.10.0 documentation

This article describes the following contents.

  • Single quotes: '
  • Double quotes: "
  • Difference between single quotes and double quotes
    • Both values are equal
    • Quotes in strings are handled differently
  • Triple quotes: ''', """
    • Multiple lines
    • Single and double quotes
    • Indentation
  • Convert other types to strings: str()
    • Convert numbers to strings
    • Convert lists and dictionaries to strings

Single quotes: '

Enclose the text in single quotes ' to make it a string (str).

s = 'abc'
print(s)
# abc

print(type(s))
# <class 'str'>

Double quotes: "

Also, enclose the text in double quotes " to make it a string (str).

s = "abc"
print(s)
# abc

print(type(s))
# <class 'str'>

Difference between single quotes and double quotes

Both values are equal

Whether you use single quotes ' or double quotes ", created strings are equal.

s_sq = 'abc'
s_dq = "abc"

print(s_sq == s_dq)
# True

Quotes in strings are handled differently

In a string enclosed in single quotes ', double quotes " can be used as is, but single quotes ' must be escaped with a backslash and written as \'. There is no problem if you write \" for double quotes ".

s_sq = 'a\'b"c'
print(s_sq)
# a'b"c

s_sq = 'a\'b\"c'
print(s_sq)
# a'b"c

In a string enclosed in double quotes ", single quotes ' can be used as is, but double quotes " must be escaped with a backslash and written as \". There is no problem if you write \' for single quotes '.

s_dq = "a'b\"c"
print(s_dq)
# a'b"c

s_dq = "a\'b\"c"
print(s_dq)
# a'b"c

Since it is just a difference in writing, values are equal in both cases.

s_sq = 'a\'b"c'
s_dq = "a'b\"c"

print(s_sq == s_dq)
# True

Triple quotes: ''', """

Triple quotes (''', """), that is, three single quotes ' or double quotes ", also make a string (str).

Multiple lines

An error occurs when a newline is inserted in a string enclosed in single or double quotes. To insert a newline, you need to use \n.

  • Handle line breaks (newlines) in Python

# s = 'abc
# xyz'
# SyntaxError: EOL while scanning string literal

s = 'abc\nxyz'
print(s)
# abc
# xyz

Within a string enclosed in triple quotes, line breaks can be written as they are.

s_tq = '''abc
xyz'''

print(s_tq)
# abc
# xyz

print(type(s_tq))
# <class 'str'>

Of course, it does not have to contain line breaks.

s_tq = '''abc'''
print(s_tq)
# abc

Single and double quotes

You can use " in three single quotes ''' and ' in three double quotes """. Values are equal in both cases.

s_tq_sq = '''\'abc\'
"xyz"'''

print(s_tq_sq)
# 'abc'
# "xyz"

s_tq_dq = """'abc'
\"xyz\""""

print(s_tq_dq)
# 'abc'
# "xyz"

print(s_tq_sq == s_tq_dq)
# True

Indentation

If spaces are inserted at the beginning of a line to match the indentation, created string includes spaces.

s_tq = '''abc
          xyz'''

print(s_tq)
# abc
#           xyz

There is a way to write the following using line feed and parentheses.

s_multi = ('abc\n'
           'xyz')

print(s_multi)
# abc
# xyz

See the following article for details.

  • Handle line breaks (newlines) in Python

Convert other types to strings: str()

You can use str() to convert objects of other types to strings (str).

  • Built-in Types -str() — Python 3.10.0 documentation

str() returns the result of the __str()__ method of the target object. If its type has no __str()__ method defined, it returns the result of repr().

The following are some examples of typical types.

Convert numbers to strings

Integers int and floating point numbers float can be converted to strings str with str().

i = 100

s_i = str(i)
print(s_i)
# 100

print(type(s_i))
# <class 'str'>

f = 0.123

s_f = str(f)
print(s_f)
# 0.123

print(type(s_f))
# <class 'str'>

For example, int can be written in hexadecimal, float in exponential, and so on, but when converted to a string with str(), they are converted to standard decimal strings.

i = 0xFF
print(i)
# 255

s_i = str(i)
print(s_i)
# 255

f = 1.23e+10
print(f)
# 12300000000.0

s_f = str(f)
print(s_f)
# 12300000000.0

Use the built-in function format() to convert it to a string of the desired format.

  • Built-in Functions - format() — Python 3.10.0 documentation

s_i_format = format(i, '#X')
print(s_i_format)
# 0XFF

s_f_format = format(f, '.2e')
print(s_f_format)
# 1.23e+10

If you want to convert a string of numbers to numeric values, see the following article.

  • Convert a string to a number (int, float) in Python

Convert lists and dictionaries to strings

Lists list and dictionaries dict can also be converted to strings str with str().

l = [0, 1, 2]

s_l = str(l)
print(s_l)
# [0, 1, 2]

print(type(s_l))
# <class 'str'>

d = {'a': 1,
     'b': 2,
     'c': 3}

s_d = str(d)

print(s_d)
# {'a': 1, 'b': 2, 'c': 3}

print(type(s_d))

You can use pformat() of the pprint module of the standard library to convert it to a well-formed string.

import pprint

dl = {'a': 1, 'b': 2, 'c': [100, 200, 300]}

s_dl = str(dl)
print(s_dl)
# {'a': 1, 'b': 2, 'c': [100, 200, 300]}

p_dl = pprint.pformat(dl, width=10)
print(p_dl)
# {'a': 1,
#  'b': 2,
#  'c': [100,
#        200,
#        300]}

print(type(p_dl))
# <class 'str'>

For more information about pprint, see the following article.

  • Pretty-print with pprint in Python

How do you replace single quotes with 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.

How do I convert a string to a double quote in Python?

In a string enclosed in double quotes " , single quotes ' can be used as is, but double quotes " must be escaped with a backslash and written as \" .

How do I remove single quotes from a string in Python?

replace() to remove single quotes from a string. Call str. replace(old, new) with old as "'" and new as "" to remove all single quotes from the string.

How do you replace a quote in Python?

To erase Quotes (“”) from a Python string, simply use the replace() command or you can eliminate it if the quotes seem at string ends.