Python converting '\' to '\\'

后端 未结 5 1150
耶瑟儿~
耶瑟儿~ 2021-01-27 16:46

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

相关标签:
5条回答
  • 2021-01-27 17:10

    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.

    0 讨论(0)
  • 2021-01-27 17:14

    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.

    0 讨论(0)
  • 2021-01-27 17:16

    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.

    0 讨论(0)
  • 2021-01-27 17:18

    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))
    
    0 讨论(0)
  • 2021-01-27 17:19

    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)
    
    0 讨论(0)
提交回复
热议问题