Python Learning Notes (iv) String type

Source: Internet
Author: User

The string is the most commonly used data type in Python. We can use quotation marks (' or ') to create a string.

In the latest version of Python 3, strings are encoded in Unicode, meaning that Python's strings support multiple languages.

Creating a string is simple, as long as you assign a value to the variable

View Code

For the encoding of a single character, Python provides an ord() integer representation of the function to get the character, and the chr() function converts the encoding to the corresponding character

View Code

If you know the integer encoding of a character, you can also write it in hexadecimal str :

'\u4e2d\u6587 ' ' Chinese '    

Because the Python string type is str , in memory, in Unicode, one character corresponds to a number of bytes. If you want to transfer on a network, or save to disk, you need to turn it str into bytes bytes .

Python bytes uses b a prefixed single or double quotation mark for data of type

1 >>> x = b'ABC'3 >>> type (x)4 <'bytes' >  

Note the distinction ‘ABC‘ and, the former, the b‘ABC‘ latter, str Although the content is displayed in the same way as the former, but bytes each character occupies only one byte.

The str pass method, expressed in Unicode encode() , can be encoded as specified bytes , for example:

1 >>>‘Abc'. Encode (‘Ascii‘)2 b‘Abc‘34 >>>‘Chinese'. Encode (‘Utf-8‘)5 b‘\xe4\xb8\xad\xe6\x96\x87‘67 >>> '  Chinese  ' 

Pure English str can be ASCII encoded as bytes , content is the same, containing Chinese str can be UTF-8 encoded as bytes . strcannot be encoded in Chinese ASCII because the range of Chinese encoding exceeds the range of the ASCII encoding, and Python will make an error.

In bytes , the bytes that cannot be displayed as ASCII characters are \x## displayed.

Conversely, if we read the byte stream from the network or disk, then the data read is bytes . To turn bytes str it into, you need to use the decode() method:

1 >>> b ' abc ' abc 3  \ Xe4\xb8\xad\xe6\x96\x87 ' utf-8 ' ) 5  ' 

To calculate str how many characters are included, you can use a len() function:

1 >>> len ('ABC')2 33 >>> len (' Chinese ')4 2  

len()The function calculates the str number of characters, and if bytes so, the len() function calculates the number of bytes:

1 >>> len (b'ABC')2 33 >>> len (b'\xe4\xb8\xad\xe6\x96\x87') )4 65 >>> len (' Chinese '. Encode ('utf-8'))6 6  

As can be seen, 1 Chinese characters are UTF-8 encoded and typically consume 3 bytes, while 1 English characters take up only 1 bytes.

We often encounter str and convert to and bytes from each other when manipulating strings. In order to avoid garbled problems, we should always adhere to the use of UTF-8 encoding str and bytes conversion.

Because the Python source code is also a text file, so when your source code contains Chinese, it is important to specify that you save it as UTF-8 encoding when you save it. When the Python interpreter reads the source code, in order for it to be read by UTF-8 encoding, we usually write these two lines at the beginning of the file:

#!/usr/bin/env python3# -*-coding:utf-8-*-  

The first line of comments is to tell the Linux/os x system that this is a python executable and the Windows system ignores this comment;

The second line of comments is to tell the Python interpreter to read the source code according to the UTF-8 encoding, otherwise the Chinese output you write in the source code may be garbled.

Affirming that UTF-8 encoding does not mean that your .py file is UTF-8 encoded, you must also make sure that the text editor is using UTF-8 without BOM encoding

If the .py file itself uses UTF-8 encoding and is also stated # -*- coding: utf-8 -*- , open a command prompt test to display Chinese correctly

Accessing values in a string

Python to access substrings, you can use square brackets to intercept strings

1 >>> v1 =‘Hello World‘2 >>> v2 = "hello python" 3 4 >>> print (  "v1[0] is%s"% V1[0]) 5 >>> print (  "v2[1:5" is%s "% V2[1:5 6 7 8 v1[0]  H9 V2[1:5" Span style= "color: #0000ff;" >is Ello               

Python uses a backslash (\) to escape characters when special characters are needed in characters

Escape character Describe
\ (at end of line) Line continuation character
\\ Backslash symbol
\‘ Single quotation marks
\" Double quotes
\a Bell
\b BACKSPACE (Backspace)
\e Escape
\000 Empty
\ n Line break
\v Portrait tab
\ t Horizontal tab
\ r Enter
\f Page change
\oyy Octal number, the character represented by YY, for example: \o12 for newline
\other Other characters are output in normal format
\xyy Hexadecimal number, the character represented by YY, for example: \x0a for line break

String operators

The variable a value is the string "Hello", and the B variable value is "Python" for example:

Operator Describe Instance
+ String connection A + B output result: Hellopython
* Repeating output string A*2 Output Result: Hellohello
[] Getting characters in a string by index A[1] Output result e
[ : ] Intercept part of a string A[1:4] Output results ell
Inch Member operator-Returns TRUE if the string contains the given character H in a output result 1
Not in Member operator-Returns TRUE if the string does not contain the given character M Not in a output result 1
R/r Raw string-Raw string: all strings are used directly as literal meanings, without escaping special or non-printable characters. The original string has almost exactly the same syntax as a normal string, except that the first quotation mark of the string is preceded by the letter "R" (which can be case). print R ' \ n ' output \ n and print R ' \ n ' output \ n
% format string

Instance:

View Code

The result of the execution is:

View Code

Python Learning Notes (iv) String type

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.