Home > Back-end >  Is there a shortcut to convert plain text list into a python list? ( strings with comma)
Is there a shortcut to convert plain text list into a python list? ( strings with comma)

Time:04-02

I'm copying and pasting this list of hex codes, and I want to format it into a python list more easily than going through and typing ' ', around each one. Are there any shortcuts for this? It's fine for a short list, but for a longer list, this would be tedious

input:

#ffa600
#ff8538
#ff6959
#f05675
#d0508a
#a85196
#7a5296
#4d508b
#244a76
#01405d

desired output:

list = ['#ffa600', '#ff8538', etc]

CodePudding user response:

I usually use python interepreter for this kind of job. Using triples quotes makes it easier.

input = """#ffa600
#ff8538
#ff6959
#f05675
#d0508a
#a85196
#7a5296
#4d508b
#244a76
#01405d
"""
output = input.split("\n")

Leads to this list that you can copy paste

output = ['#ffa600', '#ff8538', '#ff6959', '#f05675', '#d0508a', '#a85196', '#7a5296', '#4d508b', '#244a76', '#01405d']

CodePudding user response:

Use str.splitlines

>>> d = """\
... abc
... def
... ghi
... """
>>> d.splitlines()
['abc', 'def', 'ghi']

CodePudding user response:

First copy all of your hex values to a text file as test.txt

test.txt:

#ffa600
#ff8538
#ff6959
#f05675

Now read each line in text file with a for loop

f = open("test.txt", "r")
my_list = []
X=0

for i in f.readlines(): 
    my_list.insert(x, i.rstrip("\n")) 
    x=x 1
f.close()

print("list =", my_list)

Output:

list = ['#ffa600','#ff8538','#ff6959','#f05675']
  • Related