Python Forum

Full Version: Trying to understand strings and lists of strings
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Lets say we have a string a = "apple" and we wish to add this variable in a list fruits = [], using fruits.append(a). But when we print the list, the string "apple" is stored like this in the list, ['apple']. So my question now is, why does python not store strings in double qoutes " " instead of single qoutes ' ' inside a list? or is there a workaround to store strings with double qoutes inside a list? like what's the process behind storing strings in an array or list
The single or double quotes are not really part of the string, rather display helps. Python will use single quotes by default, but use double quotes if needed (if the string contains a single quote/apostrophe for example). See:
fruits = []
first = "ap'ple"
second = "grape"
third = "pear"
fruits.append(first)
print(fruits)
fruits.extend([second, third])
print(fruits)
Output:
["ap'ple"] ["ap'ple", 'grape', 'pear']
And, to access the first character of the first item in fruits[] you would access fruits[0][0] and get the letter a. No quotes, single or double.
It prints single quotes because that is what str.__repr__() uses to mark the start and end of the string.
def print_string(string):
    print(string, repr(string))

print_string("apple")
print_string('apple')
print_string("""apple""")
Output:
apple 'apple' apple 'apple' apple 'apple'
When you print a string, Python calls str.__str__() to get a pretty representation of the str object. The pretty representation has no surrounding quotes. When you print a list of strings, Python calls str.__repr__() to get a more informative representation of the string. The informative representation is enclosed in single quotes to tell the user 'This is a str object'.

The quote characters at the start and end of a string literal are not part of the string. They are there to tell Python where the string starts and ends. When Python converts the string literal to a str object, the new str object doesn't have any quotes.