Python3 String Learning Tutorial

Source: Internet
Author: User
The string type is the most common type in Python, is an immutable type, supports single quotes, double quotes, three quotation marks, a pair of consecutive single or double quotation marks, and allows a string to span multiple lines.
String Connection: The above mentioned + operator can be used for string connections, you can also directly concatenate several strings together, and call the Join () method can also connect strings.
Operators that apply only to string joins: In addition to the operators that are common to some sequence types, strings have only their own operators, including the format control operator%, string template strings. Template, primitive string operator r/r, Unicode string operator u/u.

The following is a list of the modules related to string types.
String: Strings manipulate related functions and tools, such as the template class.
Re: Regular expression, powerful string pattern matching module.
struct: A switch between a string and a binary.
C/stringio: A string buffer object that operates like a file object.
BASE64:BASE16,32,64 Data codec.
Codecs: Decoder registration and base class.
Crypt: a unilateral encryption.
Difflib: Find out the difference between sequences.
Hashlib: api,python2.5 Abolition of many different security systems and information digest algorithms.
Python implementation of HMA:HMAC information authentication algorithm.
Md5:rsa MD5 Information Digest authentication.
Rotor: Provides multi-platform encryption and decryption services.
Sha:niat's Secure ha system algorithm sha.
Stringprep: Provides a Unicode string for the IP protocol.
TextWrap: Text wrapping and padding.
Unicodedata:unicode database.

Python 3 's source code is the default encoding method of UTF-8
In Python 3, all strings are sequences of characters that use Unicode encoding.
Utf-8 is a way to encode characters into a sequence of bytes. Bytes are bytes, not characters. Characters are only an abstraction within a computer. The string is an abstract sequence. Here we discuss only the string, not the byte.

In Python, strings can be enclosed in single quotes or double quotes, or even three quotes.
But if the string contains single quotes, you should enclose them in double quotation marks, or enclose them in an escaped multibyte single quotation mark. The same with double quotes.
A string of three quotes can be wrapped!

String is not modifiable, this is important! You can think of it as a tuple of characters.

>>> s = "HelloWorld" >>> s[0] = ' h ' Traceback (most recent call last):  File "
 
  
   
  ", line 1 , in 
  
   
    
      s[0] = ' h ' TypeError: ' str ' object does not support item assignment 
  
   
 
  

If you want to modify it, you can convert it to a list, and then change to a string after the modification is complete.

The string can be directly spliced, but if it is a string represented by two variables, you should use the + number.

>>> s = "Hello" "World" >>> s ' HelloWorld ' >>> s1 = "Hello" >>> s2 = "World" >>&G T S1s2 Traceback (most recent):  File "
 
  
   
  ", line 1, in 
  
   
    
      s1s2 nameerror:name ' s1s2 ' is Not defined >>> s1+s2 ' HelloWorld ' 
  
   
 
  

String Operations and methods:
Len (s) returns the string length
X in S queries if x is in S

S.find (x) finds the substring X in the string s, returns the leftmost index, and returns 1 if not found

S.splitlines () splits a multiline string into a list of multiple single-line strings, and the newline character is absorbed

S.split (x) splits s into a list of strings with x as a delimiter, and if X is not provided, the program automatically splits all spaces and line breaks as separators

S.lower () returns the lowercase string of s
S.upper () returns the uppercase string of s

S.join (seq) split inverse method, which connects sequence seq with S, must be a string sequence

S.replace (x, y) replaces all occurrences of x in S with Y, and if not found, returns s directly

S.strip (x) If x is not provided, returns a string that removes the space between the end and the end, and if a string x is supplied, all the characters in X are stripped and returned

>>> s = "  hi,i ' m alice!  

Again note: The above method has not changed the original string, the string is immutable!

Here's a quick look:
S.starstwith (x) tests if s begins with X
S.endswith (x) tests if s end with X
S.isalnum () Tests whether s are all letters and numbers, and has at least one character
S.isalpha () Tests if s are all letters, and has at least one character
S.isdigit () Tests if s are all numbers and has at least one character
S.isspace () Tests if s are all whitespace characters and has at least one character
S.islower () test if the letters in s are all lowercase
S.isupper () tests if the letters in S are uppercase
S.istitle () to test if S is an initial capital letter

Let's focus on a powerful formatting method format, see the code below

(1) In the sentence, {0} in the string is replaced by the first parameter of format, and {1} is replaced by the second parameter. Two parameters not enough? In fact, you can give it any number of arguments and replace it with the same number of replacement fields. What is a replacement field? {0},{1} is called a replacement field. We used 3 substitution fields in paragraph (2), {0} corresponds to name, {1} corresponds to call,{2} corresponding to addr. A few more parameters are similar to what has just been done.
So, is that just it? Of course not! Let's keep looking.

{0[0]} means l[0],{0[2]} means l[2], which are called compound field names, you can:
(1) Use a list as a parameter and access its elements via subscript index (similar to the previous example)
(2) using a dictionary as a parameter and accessing its value by key

D is the dictionary, a, B is the key, {0[a]} corresponds to the value 2 (Note: Yes, a, not ' a ', ' B ')
(3) Use the module as a parameter, and access its variables and functions by name

>>> print ("{0.random}". Format (Random)) 
 
   
 
  

(4) Use an instance of the class as a parameter, and access its methods and properties by name

>>> class A:   pass  >>> x = A () >>> Print ("The class is {0.__class__}". Format (x)) the CLA SS is 
 
   
 
  

(5) Any combination of the above methods

Replace field in addition to integers, you can also use parameter names

In the replacement field, you can also use the format specifier. Colon: Indicates the beginning of the format specifier.

>>> pi = 3.141592653 >>> print ("The pi is {0:10.3f}". Format (PI)) # 0:10.3f indicates an output width of 10, retains three decimal places, floating-point number the pi I S   
  • 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.