问题
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å i'm using a the ability to apply a function to each element during sort. like this:
# -*- coding: UTF8 -*-
def conv( inp ):
if inp == '$\lambda$':
return 'lambda'
else:
return inp
mlist = []
mlist.append('martin')
mlist.append('jenny')
mlist.append('åse')
mlist.append('$\lambda$')
mlist.append('lambda')
mlist.append('\her')
print (mlist)
mlist = sorted(mlist, key=conv(str.lower))
print (mlist)
But for some reason, when i append the lambda
sign or \her
it converts it to \\her
or $\\lambda$
, can i prevent this?
回答1:
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.
回答2:
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.
回答3:
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.
回答4:
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))
回答5:
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)
来源:https://stackoverflow.com/questions/6968382/python-converting-to