1, string
1. 1. How to use strings in Python
A, use single quotation marks (')
Enclose the string in single quotation marks, for example:
Str=' This is a string';
Print string; B. Use double quotation marks (")
The string in double quotation marks has exactly the same usage as the string in single quotation marks, for example:
Str= "This is a string";
Print string;
C, use three quotation marks ("")
Use three quotation marks to represent multi-line strings. You can freely use single quotation marks and double quotation marks in the three quotation marks, for example:
Str=''' This is a string.
This is the Pissode string
This is the string'''
Print string; 2. Boolean type
bool = False
Print bool
bool = True
Print bool3. integer
int = 20
Print int4, floating point number
float = 2.3
Print floating; 5. Numbers
Include integer and floating-point numbers.
5. 1, delete the digital object reference, for example:
a = 1;
b = 2;
c = 3;
del a;
del b,c;
# print a; # After deleting variable A, calling variable A again will cause an error. 5.2. Digital type conversion.
Int(x [,base]) converts x into an integer.
Float(x) converts x into a floating point number.
Complex(real [,imag]) creates a complex number.
Str(x) converts the object x into a string.
Repr(x) converts object x into an expression string.
Eval(str) is used to evaluate a valid Python expression in a string and return an object.
Tuples convert the sequence s into tuples.
Convert a sequence into a list.
Chr(x) converts integers into characters.
Unicode) converts integers into Unicode characters.
Ord(x) converts a character into its integer value.
Hex(x) converts an integer into a hexadecimal string.
Oct(x) converts integers into octal strings 5.3. mathematical function
Abs(x) returns the absolute value of a number. For example, abs(- 10) returns 10.
Ceil(x) returns a numeric integer, for example, math.ceil(4. 1) returns 5.
If x, Cmp(x, y); Y returns 1.
Exp(x) returns e to the power of x (ex), for example, math.exp( 1) returns 2.718281828459045.
Fabs(x) returns the absolute value of a number, such as math.fabs(- 10) returns 10.0.
Floor(x) returns a rounded integer of a number, for example, math.floor(4.9) returns 4.
Log(x) such as math.log(math.e) returns 1.0, and math.log (100, 10) returns 2.0.
Log 10(x) Returns the logarithm of x based on 10. For example, math.log 10( 100) returns 2.0.
Maximum value (x 1, x2, ...) returns the maximum value of a given parameter, which can be a sequence.
Min(x 1, x2, ...) returns the minimum value of a given parameter, which can be a sequence.
Modf(x) returns the integer part and the decimal part of x, whose numerical sign is the same as X, and the integer part is expressed as a floating point.
The value after pow(x, y) x**y operation.
Round(x [,n]) returns the rounded value of floating-point number X. If n is given, it means the number of digits rounded to the decimal point.
Sqrt(x) returns the square root of the number x, which can be negative, and the return type is real, such as math.sqrt(4) returns 2+0j6 and list.
6. 1, initialize the list, for example:
List=[' physics',' chemistry',1997,2000];
nums=[ 1,3,5,7,8, 13,20]; 6.2. Access the values in the list, for example:
' ' ' nums[0]: 1 ' ' '
Print "nums[0]:", nums[0]
Nums[2:5]: [5, 7, 8] Cut from the element with subscript 2 to the element with subscript 5, but excluding the element with subscript 5.
Print "nums[2:5]:", nums[2:5]
Nums [1:]: [3,5,7,8,13,20] Cut from subscript1to the last element'''
Print "nums[ 1:]:", nums[ 1:]
Nums[:-3]: [1, 3, 5, 7] cuts from the initial element to the penultimate element, excluding the penultimate element "".
Print "nums[:-3]:", nums[:-3]
'' nums [:]: [1, 3,5,7,8,13,20] returns all elements'''
Print "nums[:]:", nums[:]6.3. Update the list, for example:
nums[0]= " ljq ";
Print num [0]; 6.4. Delete list elements
del nums[0];
' ' ' nums[:]: [3,5,7,8, 13,20]' ' '
Print "nums[:]:", nums [:]; 6.5. List Script Operators
The operators of list pairs+and * are similar to strings. The+symbol is used to combine lists, while the * symbol is used to repeat lists, for example:
Print lens ([1, 2,3]); #3
print [ 1,2,3] + [4,5,6]; #[ 1, 2, 3, 4, 5, 6]
Print [Hi! ]] * 4; # ['Hi!' ,' Hi!' ,' Hi!' ,' Hi!' ]
print 3 in [ 1,2,3] #True
For x in [1, 2,3]: print x, # 1 236.6, and the list is truncated.
L=['spam ',' spam ',' Spam!' ];
Print l [2]; #' Spam!'
Print l [-2]; #' Spam'
Print l [1:]; # ['Spam',' Spam!' ]6.7. List function &; way
List.append(obj) adds a new object at the end of the list.
List.count(obj) counts the number of times an element appears in the list.
List.extend(seq) Appends multiple values to another sequence at the end of the list (extending the original list with a new list).
List.index(obj) finds the index position of the first match of the value from the list, and the index starts from 0.
Inserts an object into the list.
List.pop(obj=list[- 1]) removes an element from the list (the last element by default) and returns its value.
List.remove(obj) removes the first value in the list.
List.reverse () inverts the elements in the list.
List.sort([func]) sorts the original list 7. Tuple.
Python tuples are similar to lists, except that the elements of tuples cannot be modified; Use parentheses () for tuples and [] for lists; Tuple creation is simple, just add elements in brackets and separate them with commas (,), for example:
Tup 1 = ('physics',' chemistry',1997,2000);
tup2 = ( 1,2,3,4,5);
tup3 = "a "," b "," c "," d "; Create an empty tuple, for example: tup = ();
When a tuple has only one element, you need to add a comma after the element, for example: tup 1 = (50,);
Tuples are similar to strings, and the subscript index starts from 0, which can be intercepted, combined and so on.
7. 1, access tuple
Tup 1 = ('physics',' chemistry',1997,2000);
#tup 1[0]: physics
Print "tup 1[0]:", tup 1[0]
#tup 1[ 1:5]: ('chemistry', 1997)
Print "tup 1 [1: 5]:", tup 1 [1: 3] 7.2. Modify tuples.
Element values in tuples are not allowed to be modified, but we can connect combined tuples, for example:
tup 1 = ( 12,34.56);
tup2 = ('abc ',' XYZ ');
# The following operations to modify tuple elements are illegal.
# tup 1[0]= 100;
# Create a new tuple
tu P3 = tup 1+tu p2;
Print tup 3 # (12,34.56,' Agricultural Bank of China',' XYZ') 7.3. Delete tuples.
Deleting element values in tuples is not allowed. Del statement can be used to delete the whole tuple, for example:
Tup = ('physics',' chemistry',1997,2000);
Print tup
Deltup; 7.4, tuple operator
Like strings, tuples can be manipulated with+and * symbols. This means they can be combined and copied, and a new tuple will be generated after the operation.
7.5. Tuple index &; intercept
L = ('spam ',' spam ',' Spam!' );
Print l [2]; #' Spam!'
Print l [-2]; #' Spam'
Print l [1:]; # ['Spam',' Spam!' ]7.6, tuple built-in function
Cmp(tuple 1, tuple2) compares two tuple elements.
Len(tuple) counts the number of tuple elements.
Max(tuple) returns the maximum value of an element in a tuple.
Min(tuple) return that minimum value of the elements in the tuple.
Tuple(seq) converts a list into a tuple. 8. Dictionary
8. 1, dictionary introduction
Dictionary is the most flexible built-in data structure type in python except list. A list is an ordered combination of objects, while a dictionary is an unordered collection of objects. The difference between the two is that the elements in the dictionary are accessed by keys, not by offsets.
A dictionary consists of keys and corresponding values. Dictionaries are also called associative arrays or hash tables. The basic syntax is as follows:
Dict = {'Alice':' 234 1',' Beth':' 9 102',' Cecil':' 3258'}; You can also create a dictionary like this:
dict 1 = { ' ABC ':456 };
dict2 = { 'abc': 123,98.6:37 }; Each key and value must be separated by a colon (:), each pair by a comma, and the whole key is enclosed in braces ({}). The key must be unique, but the value is not. Values can take any data type, but they must be immutable, such as strings, numbers or tuples.
8.2. Access the values in the dictionary
#! /usr/bin/python
dict = {'name': 'Zara ',' age': 7,' class ':' First ' };
Print "dict[' name']:", dict[' name'];
Print "dict['age']:", dict ['age']; 8.3, modify the dictionary
The way to add new content to the dictionary is to add new key/value pairs and modify or delete existing key/value pairs, as shown below:
#! /usr/bin/python
dict = {'name': 'Zara ',' age': 7,' class ':' First ' };
Dict[ "age"] = 27; # Modify the value of an existing key
Dict[ "school"] = "Wu Tong"; # Add a new key/value pair
Print "dict['age']:", dict ['age'];
Print "dict[' school']:", dict[' school']; 8.4. Delete the dictionary
del dict[' name ']; # Delete the entry with the keyword "name"
dict . clear(); # Clear all entries in the dictionary
Del dict# Delete dictionary, for example:
#! /usr/bin/python
dict = {'name': 'Zara ',' age': 7,' class ':' First ' };
del dict[' name '];
#dict {'age': 7,' class': 'First'}
Print "dict", dict; Note: The dictionary does not exist, and del will throw an exception.
8.5, dictionary built-in function &; way
Cmp(dict 1, dict2) compares two dictionary elements.
Len(dict) calculates the number of dictionary elements, that is, the total number of keys.
The Str(dict) output dictionary can print string representation.
Type(variable) returns the type of the input variable, or the dictionary type if the variable is a dictionary.
Radiansdict.clear () deletes all elements in the dictionary.
Radiansdict.copy () returns a shallow copy of a dictionary.
Radiansdict.fromkeys () creates a new dictionary, with the elements in the sequence seq as the keys of the dictionary and val as the initial values corresponding to all keys of the dictionary.
Radiansdict.get (key, default = none) returns the value of the specified key, or the default value if the value is not in the dictionary.
Radiansdict.has_key(key) If the key in the dictionary dict returns true, otherwise it returns false.
Radiansdict.items () returns a traversable array of (key, value) tuples as a list.
Radiansdict.keys () returns all the keys of a dictionary as a list.
Radiansdict.setdefault (key, default = none) is similar to get (), but if the key does not exist in the dictionary, it will be added and the value will be set to default.
Radiansdict.update(dict2) updates the key/value pair of dict2 to dict.
Radiansdict.values () returns all the values 9, date and time in the dictionary as a list.
9. 1, get the current time, for example:
Import time, date and time.
Local time = time. Local time (time. time ())
# local current time: time. struct _ time (TM _ year = 2014, tm_mon=3, tm_mday=2 1, tm_hour= 15, TM _ min =1.
Print "local current time:" and local time description: time. struct _ time (TM _ year = 20 14,TM _ mon = 3,TM _ mday = 2 1,TM _ hour = 15,TM _ min = 65438。 TM _ sec = 56, TM _ wday = 4, TM _ yday = 80, TM _ isdst = 0) belongs to the struct_time tuple, which has the following properties:
9.2, get the formatting time
You can choose any format you want, but the simplest function to get a readable time pattern is asctime ():
2. 1, the date is converted into a string.
First choice: printtime.strftime ('%y-%m-%d% h:% m:% s');
Second: print the date and time. datetime . strfttime(datetime . datetime . now(),' % y-%m-%d% h:% m:% s ')
Finally: print the string (date and time. datetime.now ()) [: 19]
2.2, the string is converted into a date.
expire _ time = " 20 13-05-2 1 09:50:35 "
d = datetime . datetime . strptime(expire _ time," %Y-%m-%d %H:%M:%S ")
Print d; 9.3. Difference of acquisition date
Oneday = datetime.timedelta (days = 1)
# Today 20 14-03-2 1
Today = date time. Date. Today ()
# Yesterday 20 14-03-20
Yesterday = date time. Date. Today ()-a day.
# Tomorrow, 20 14-03-22
Tomorrow = date time. Date. Today ()+one day.
# Get the time of today's zero, 20 14-03-2 1 00: 00.
today _ zero _ time = datetime . datetime . strftime(today,' %Y-%m-%d %H:%M:%S ')
#0:00:00.00 1000
Printdatetime.timedelta (ms = 1), # 1 ms.
#0:00:0 1
Printdatetime.timedelta (seconds = 1), # 1 second.
#0:0 1:00
Printdatetime.timedelta (minutes = 1), # 1 minute.
# 1:00:00
Printdatetime.timedelta (hour = 1), # 1 hour.
# 1 day, 0:00:00
Printdatetime.timedelta (days = 1), # 1 day.
#7 days 0:00:00
Print datetime.timedelta (weeks =1)