paranormaldist
paranormaldist

Reputation: 508

Understanding string generation of double vs single quotes

I'm trying to understand why sometimes double quotes are being generated vs single quotes for my list creation function. I have a function that I've used on multiple text files and normally the output is a list with single quotes, but now double quotes are generated (when I need single).

Would someone be able to help me understand why double quotes might be generated here and/or a way to just force the single quotes?

for below structure is :
string_text is str
text_list is list
list_text is list

def view(string_text):
   text_list = []
   for t in list_text:
       text_list.append(string_text + """   more text """ + t + 
                        """ more text """)
   return text_list
text_list = view(string_text)

The append is specific to my use case, but you get the idea. Double quotes are generated for text_list.

list_text sample = ['a','b','c']

Upvotes: 0

Views: 56

Answers (2)

glglgl
glglgl

Reputation: 91159

So let's turn your code into something which can directly be pasted into a python console window:

def view(string_text):
    text_list = []
    for t in list_text:
        text_list.append(string_text + """   more text """ + t +
                         """ more text """)
    return text_list

list_text = ['a', 'b', 'c']
text_list = view('123')
text_list

shows

['123   more text a more text ', '123   more text b more text ', '123   more text c more text ']

Why? Because the string representation of a string uses ' until there is a ' contained in the string. Then it uses " for delimiting the string.

Simpler examples are

>>> "'"
"'"
>>> '"'
'"'
>>> "'\""
'\'"'

But it shouldn't make a difference. As said, this is just the string representation of a string which exists in your program. These delimiters aren't really in the string itself. See the difference between what str() and repr() do, respectively.

Upvotes: 1

Keine_Eule
Keine_Eule

Reputation: 147

It is not an explanation of why this occurs, but maybe a solution: If you wrap another str() around your string (double or single quoted), the result should always be single quoted, at least when I tried it.

Upvotes: 1

Related Questions