David_Hercules
David_Hercules

Reputation: 23

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.

Upvotes: 0

Views: 18207

Answers (4)

Cesar
Cesar

Reputation: 585

The following will work with numeric or string based lists (tested in Python 3.8.2):

lstNumbers = [10, 20, 30]
lstNumbersQuoted = [f'{str(i)}' for i in lstNumbers]
print(lstNumbersQuoted)

['10', '20', '30']

Note that f'{str(i)}' is Python f-string (formatted string literals) format.

Upvotes: 2

Alejandro García
Alejandro García

Reputation: 81

It's been a while, but I think I've found a quick way following @U10-Forward's idea:

>>> list = ('A B C D E F G Hola Hello').split()
>>> print(list)

['A', 'B', 'C', 'D', 'E', 'F', 'G', 'Hola', 'Hello']

Upvotes: 0

U13-Forward
U13-Forward

Reputation: 71600

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

Upvotes: 6

Nikith Kumar
Nikith Kumar

Reputation: 3

You can take input as string and split it to list For eg.

eg="This is python program"
print(eg)
eg=eg.split()
print(eg)

This will give output

This is python program

['This', 'is', 'python', 'program']

Hope this helps

Upvotes: 0

Related Questions