I am writing a program to sort a list fo input strings (song names). Those songnames contains latex chars like $\\lambda$, which i want to get sorted like \'lambda\' instead, s
But for some reason, when i append the
lambda
sign or\her
it converts it to\\her
or$\\lambda$
...
No it doesn't. What you're seeing is the representation, which always doubles solo backslashes for clarity. If you print the actual strings instead you'll see that they're fine.
There is nothing wrong with the code: what you're experiencing is repr
behaviour. Printing a list causes it's contents to be repr'd, and repr
escapes \
.
print repr(r'\foo') # => '\\foo'
If you want to print the list without repr
, you use either a loop or str.join.
As already suggested you should escape your backslash:
'$\\lambda$'
Another alternative is to use raw strings, which are not subject to special character substitution:
r'$\lambda$'
When you have many backslashes raw strings tend to be clearer.
This is the expected behaviour: as it is displaying the string stored in the list, and the double slashes means escaped slash. If you want to see the actual string, you should simply print that string, not the list. Try to append this line to your program:
print (' '.join(mlist))
The point is that you should use r'$\lambda$'
moreover when you print the list it print a repr of each element to print
you should do
from __future__ import print_function
print (*mlist)