How do I sort these string elements without quoting them manually?

I have Python 3.11 on Windows 10.

I have a list of strings in a text editor that I would like to sort, but my text editor (Notepad++) cannot sort strings separated by commas. The strings look like this:
LFW1, LKI1, LLA1, LNR1, LPE1, PINC, LPT1, LSW1, LSA1, LE404, LE405, LE408, P1, P2, GWH1

I tried to sort them like this in REPL.

>>> print(sorted(LFW1, LKI1, LLA1, LNR1, LPE1, PINC, LPT1, LSW1, LSA1, LE404, LE405, LE408, P1, P2, GWH1))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'LFW1' is not defined
>>>

But I got an error because each string needs to be quoted.

  1. Is there a fast automated way to quote these strings to sort them?
  2. Is there another way to sort them?

Thank you!

>>> ", ".join(sorted(input().split(", ")))
LFW1, LKI1, LLA1, LNR1, LPE1, PINC, LPT1, LSW1, LSA1, LE404, LE405, LE408, P1, P2, GWH1
'GWH1, LE404, LE405, LE408, LFW1, LKI1, LLA1, LNR1, LPE1, LPT1, LSA1, LSW1, P1, P2, PINC'

That suitable?

1 Like

A text editor search/replace from , to , or to ", " and adding the first and last one manually often does the job.

1 Like

That worked! Thanks.

1 Like

Another approach, if you want a one-liner or don’t want to rely on input() or even dropping into the REPL first:

echo <strings> | python -c 'import sys;print(", ".join(sorted(sys.stdin.read().strip().split(", "))))'

Or if you’ve already got the strings in their own text file:

python -c 'print(", ".join(sorted(Path("FILEPATH").read_text().strip().split(", "))))'

In Python and Perl I sometimes very long regular expressions with 40-50+ codes on it. It helps to sort these codes in the regex to make sure they are not duplicated. I suspect duplicates may slow down the regex processing.

Here’s a little Python (3.11) program I wrote to sort a comma separated list of codes.

VER="2025-05-02.01"
APPTITLE = "Sort comma-sep text."
print(f"v{VER} This sorts text separated by commas, for a regex.")
print("\n")

intext = "LBK1, LFJ2, AAB, AC1, FGK2, HGA1" # Enter your text to sort here.

outarr = intext.split(", ")
outarr = sorted(outarr)
outre = "|".join(outarr)
outcomma = ",".join(outarr)
print(f"Sorted Regex would be: {outre}")
print(f"Sorted comma sep: {outcomma}")