pythonstringlistquotesnameerror

Python: How to add single quotes to a long list


I want to know the quickest way to add single quotes to each element in a Python list created by hand.

When generating a list by hand, I generally start by creating a variable (e.g. my_list), assigning it to list brackets, and then populating the list with elements, surrounded by single quotes:

my_list = []

my_list = [ '1','baz','ctrl','4' ]

I want to know if there is a quicker way to make a list, however. The issue is, I usually finish writing my list, and then go in and add single quotes to every element in the list. That involves too many keystrokes, I think.

A quick but not effective solution on Jupyter NB's is, highlighting your list elements and pressing the single quote on your keyboard. This does not work if you have a list of words that you want to turn to strings, however; Python thinks you are calling variables (e.g. my_list = [1, baz, ctrl, 4 ]) and throws a NameError message. In this example, the list element baz would throw:

NameError: name 'baz' is not defined

I tried this question on SO, but it only works if your list already contains strings: Join a list of strings in python and wrap each string in quotation marks. This question also assumes you are only working with numbers: How to convert list into string with quotes in python.

I am not working on a particular project at the moment. This question is just for educational purposes. Thank you all for your input/shortcuts.


Solution

  • Yeah but then why not:

    >>> s = 'a,b,cd,efg'
    >>> s.split(',')
    ['a', 'b', 'cd', 'efg']
    >>> 
    

    Then just copy it then paste it in

    Or idea from @vash_the_stampede:

    >>> s = 'a b cd efg'
    >>> s.split()
    ['a', 'b', 'cd', 'efg']
    >>>