Python Quick Start Notes (2): Data Types

This series of essays is my study notes, beginner stage will inevitably be understood inappropriate, wrong place kindly correct me. Please indicate the source: https:////www.cnblogs.com/itwhite/p/12291087.html .

Brief introduction

Python in the list of data types:

  • Integer type, for example: 123, -456
  • Floating-point type, for example: 3.14
  • Boolean types, including only two values ​​True and False
  • None, including None only a value indicating a null value
  • String, for example: 'aaa', "BBB", '' 'ccc' '', "" "DDD" ""
  • List (array), for example: [ "Jack", "Bob", "Linda"]
  • Tuple (tuple), e.g. :( "Jack", "Bob", "Linda")
  • dictionary

Wherein: strings, lists (arrays) and tuples and referred to as "sequence", "sequence" support indexing, slicing operation.

Python use type () built-in function can return a string indicating the data type, for example:

>>> type(123)
<type 'int'>

 

String type

Python, strings by a single quote ( '), double quote ( "), three quotation marks (' '' or '' ') surrounded by:

  • Single quotes: Python in single quotes and double quotes is almost no difference (this is different from the shell and perl), which still escape character is the escape character, for example: 'a \ nb' represents a, line breaks, b three character string composed.
  • Double quotes: with single quotes.
  • Three marks: string can refer to a plurality of lines, for example:
"""
This is a mult-line
string
"""

Python string default ASCII encoding, in addition users can also specify the string prefix to tell the interpreter how to parse encoding format:

  • Use u or U prefix indicating Unicode encoding, for example: u "Chinese" (if you do not write, print out may be garbled);
  • Use b or B prefixes, which is byte value represents, for example: b "\ x41 \ x42 \ x43" (equivalent to "ABC")
  • Use prefix r or R, represents a raw string, the string \ no longer used as an escape symbol, for example: r "\ n \ t" (corresponding to "\ n \ t")

In addition, if you are using Chinese string in your code, be sure to save the file as utf-8 format and file header (first line or second line) with " encoding declaration " (to tell the interpreter to source file encoding format).

String common operations

operating Examples
Seeking string length len("string")
String concatenation s1 + s2
String comparison == s1 s2
String search

"string".find("ri") # 返回 2
re.search(r"b.c", "abbbcd")

String split

"Jack,Bob,Lucy".split(",")
re.split(r"pattern", string)

String replacement s2 = s1.replace('old', 'new')
To reverse a string string[::-1]
String sections "String" [1: 3] Back "tr", refer to the "sequence"
Gets the position of the character

string[1]

Traversal character string

for c in string:
    print c

Case conversion

"aaa".upper()、"BBB".lower()

After dropping both ends of whitespace

"  abc  ".strip() 返回 "abc"
"  abc  ".rstrip() 返回 "  abc"
"  abc  ".lstrip() 返回 "abc  "

Format string

 Example:

# Method one: The title C language printf () format, a tuple behind% 
>>> " My name IS% S,% D years the I'm Old " % ( " Jack " , 23 is )
 " My Jack iS name, the I'm years Old 23 is " 

# two: format () method, a method in {} represents the index of passed parameters, the method is similar to the reverse index n in formula 
>>> " {3 {0} {2} {} {}. 3. 1} {0} " .format ( " BE " , " Not " , " or " , " to " )
 ' to Not to BE or BE '
>>> "foo {} {} {} {} bar " .format (. 1, 2,. 4 bar =, = foo. 3)   # defined names and names will be omitted 
' . 3. 1. 4 2 ' 
>>> " {name} {Approximately value IS :. .2f} " .format (value = 3.1415926, name = " the PI " ) # also specify the accuracy of 
' the PI IS Approximately 3.14. '

 

 

List (array) type

Python in the "List" (list) that is in other languages, "array", fuck! Example:

foo = ["Jack", 23, "male"]
bar = [1, 2, 3, 4]
qux = ["Tokyo", "London", "Beijing", "Paris"]

Common array operations (table will be used in the example above example code):

operating Examples
 Seeking array length  len (foo)
 Access specified element  foo[1] = 24
 Delete the specified element

 del foo [1] # delete the specified index of the element, foo becomes [ "Jack", "MALE"]
 foo.remove (23) # 23 removes the first element of a value

 Append an element  bar.append (5) # bar becomes [1, 2, 3, 4, 5]
 Find the specified element index (first occurrence)  qux.index ( "Beijing") # returns 2
 Insert an element  qux.insert (2, "Sydney") # the "London", insert (insert new element index 2)
 Removes the last element  bar.pop () # bar becomes [1, 2, 3]
 Reverse all the elements  bar.reverse () # bar becomes [4, 3, 2, 1]
 Sorting an array  qux.sort () # qux becomes [ 'Beijing', 'London', 'Paris', 'Tokyo'], Note that sort () does not return any value, modifies the array itself 
 Array elements into a single string  "," .Join (qux) # returns the string 'Tokyo, London, Beijing, Paris'

 

Tuple type

And a list of similar sequence is also a tuple, the tuple except that the elements can not be modified (not assign a new value to the elements, i.e. elements not modify the address pointed to by the address pointing to the content may be modified in). Example:

>>> (1, 2, 3 ) 
( 1, 2, 3 )
 >>> 1, 2, 3          # can be omitted brackets 
(1, 2, 3 )
 >>> tuple ([1, 2, 3]) # converted into a list of tuples 
(. 1, 2,. 3 )
 >>> foo = (. 1, 2,. 3 )
 >>> foo [. 1] =. 4        # error, can not assign a new value for elements thereof 
Traceback (most recent call last) : 
File " <stdin> " , Line. 1, in <Module1> 
TypeError: ' tuple ' Object does Not Support Item Assignment
 >>> bar = (. 1, [2,. 3],. 4 )
 >>>    bar[1][0] = 5    #ok, it can not modify the address pointed element, it can modify the contents of the address pointed 
>>> bar 
( . 1, [. 5,. 3],. 4)

 

Dictionary Type

 

Sequence: index, sliced

Common Operation sequence functions:

function description Examples
 Only ()  Seeking sequence length  len("foo")、len([1, 2, 3])
 list()   Converting the sequence list (List Back)   list("Hello")、list((1, 2, 3))
 max()  Selecting the maximum value in the sequence  max (1, 2, 3) returns 3
 (I)  For the minimum sequence   min (1, 2, 3) returns 1
 reversed()   Returns a reverse iterator sequence  >>> reversed([1, 2, 3])
<listreverseiterator object at 0x0000000001E439E8>

>>> for x in reversed([1, 2, 3]):
...    print x
 sorted()  Returns an ordered list  the sorted ([3, 2, 1]) return [1, 2, 3]
 tuple  Sequence into the tuple (returned tuple)  tuple ([1, 2, 3]) return (1, 2, 3)

 

Finish.

Guess you like

Origin www.cnblogs.com/itwhite/p/12291087.html