Meet Python: little notes
Source: http://www.liaoxuefeng.com/
❤ Escape character: '\'
- '\n': newline;
- '\t': tab;
- '\\': \;
- r'...': no transferring for contents within single quotes;
- '''...''': multiple lines within triple quotes: could start a new line with ENTER directly. r'''...''' is valid as well.
❤ Division
- '/': floating point calculation, alway return float;
- '//': only return integer part (decimal part is direclty abandoned);
- '%': return remainder.
❤ Character encoding
- Encoding standard
.. ASCII: some symbold, number, uppercase and lowercase, 1 byte representing 1 character;
.. GB2312: Chinese character;
.. Unicode: encoding characters in all languages using one criterion, 2 bytes representing 1 character usually;
.. UTF-8: to save space, converting Unicode into 1-6 bytes (usually, one English character: 1 bytes, while one Chinses: 3 bytes); criterion used in RAM;
- Python
.. encoding using unicode;
.. for sigle character, ord() - obtaining integral representing for the character; chr() - converting code into character;
.. b'...': converting string to byte format (one byte fot each character);
.. '...'.encode('method'): encode ... using corresponding method('ascii', 'utf-8', note that Chinese characters cannot be encoded using 'ascii');
.. b'...'.decode('method'): decode byte string '...' into characters using corredponding method ('ascii', 'utf-8');
.. len('...'): obtain number of characters or bytes in '...';
.. formatting characters: the same way as c (and matlab :p):
%s - character string;
%d: integer;
%f: floating;
%x: hexadecimal integer.
some examples:
>>> 'Hello, %s' % 'world' 'Hello, world'
>>> 'Hi, %s, you have $%d.' % ('Michael', 1000000) 'Hi, Michael, you have $1000000'.
>>> '%2d-%02d' % (3, 1) '3-01' >>> '%.2f' % 3.1415 '3.14'
>>> 'Age: %s; Gender: %s' % (25, True) # If you cannot decide which placeholder to use, just use %s 'Age: 25; Gender: true'
>>> 'Growth rate: %d %%' % 7 'Growth rate: 7 %'
NOTE: we should stick to 'utf-8' for converting to avoid chaos, to ensure which: 1. make sure your text editor is using: "UTF-8 without BOM" as encoding methods; 2. add the following two lines at the beginning of your script.
#!/usr/bin/env python3 # -*- coding: utf-8 -*-