Elegant Python-code Miscellaneous: Adding u before the string

Source: Internet
Author: User
Sometimes the string we accept from other places goes through a difficult journey, and it changes. For example, you receive '\ u6253 \ u602a \ u8005' instead of U' \ u6253 \ u602a \ u8005 '. Obviously, you only need to add a U, but how to add it?> S = '\ u6253 \ u602a \ u8005'> s' \ u6253 \ u602a \ u8005 '> 'U' + s' U \ u6253 \ u602a \ \ u8005. And the surface looks like '\ u6253 \ u602a \ u8005'. In fact, it is' \ u6253 \ u602a \ u8005 'internally, which means two slashes are escaped, what I want is \ U instead of \ U. If you prefer black magic, you may think of eval.> Eval ('U "'+ S +'" ') U' \ u6253 \ u602a \ u8005'> Print eval ('U "'+ S + '"') you can use eval. However, this is too painful. Python comes with a solution. Yes Unicode-escape.> Unicode (S, 'unicode-escape ') U' \ u6253 \ u602a \ u8005' In addition, there is a name that is the same as Unicode-escape, called String-escape. The function can be said to be "Remove the Escape Character and change two backslash to one ". See the example.> S = 'Hello \ nworld'> s' Hello \ nworld'> S. Decode ('string-escape ') 'Hello \ nworld'

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.