Python string formatting and encoding and decoding issues

Source: Internet
Author: User

1%C converted to characters (ASCII value, one-length string)2 3%r Wired string conversion using the REPR () function4 5%s Wired using the str () function for string conversions6 7%dor%I convert to a signed decimal number8 9%u convert to unsigned decimal numberTen  One%o Convert to unsigned octal number A  -%x%x converted to unsigned hexadecimal number (x/x for uppercase and lowercase) -  the%e%e converted into scientific notation -  -%f%F Convert to floating-point -  +quest="What ' s your quest?" -  + ':'. Join (Quest.split ())#"What ' s:your:quest?"

The Extend () method of the list is to add a new list to the original list instead of creating a new one like a join operation

Unicode supports multiple encoding formats, such as ascii,iso8859-1/latin-1,utf-8,utf-16, whenever a string is written to a file, An encoding (encoding parameter) must be defined for the corresponding Unicode content to be converted to the defined format, and the Encode () function of the Unicode string in Python accepts the encoded format content specified by the character in the string as the parameter output.

When writing a Unicode string to disk, use the specified encoder to "encode" the File and "decode" it to make it a corresponding Unicode string object.

1file="Unicode.txt"2 3Hello_out=u"Hello world\n" #Unicode-encoded strings4 5Bytes_out=hello_out.encode ('Utf-8')#encode the file into a utf-8 encoding (binary stream form) before writing it in6 7 Print(bytes_out)#B ' Hello world\n '8 9F=open (file,"WB")#the binary stream form reads the file and cannot be read directly in string formTen #because a string (binary stream) needs to be opened in binary mode after writing UTF-8 encoding One  A f.write (bytes_out) - f.close () -  theWith open (file,'RB') as F: -bytes_in=F.read () -  -Hello_in=bytes_in.decode ('Utf-8') +  #the file needs to be decoded when reading data from a file -  + Print(hello_in)

Python string formatting and encoding and decoding issues

Related Article

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.