python data type details (comprehensive)

Keywords: Python

1. String
1.1. How to use strings in Python
a. Use single quotation marks (')
To enclose a string in single quotation marks, for example:

str='this is string';
print str;

b. Use double quotation marks (")
The use of strings in double quotation marks is identical to that in single quotation marks, for example:

str="this is string";
print str;

c. Use three quotation marks ('')
Using three quotation marks to represent multi-line strings, single quotation marks and double quotation marks can be freely used in three quotation marks, for example:

str='''this is string
this is pythod string
this is string'''
print str;

2. Boolean Type

bool=False;
print bool;
bool=True;
print bool;

3. Integers

int=20;
print int;

4. Floating Points

float=2.3;
print float;

5. Numbers
Including integers, floating-point numbers.
5.1. Delete digital object references, such as:

a=1;
b=2;
c=3;
del a;
del b, c;
\#print a; #After deleting a variable, calling a variable will cause an error.

5.2. Digital Type Conversion

int(x [,base]) converts x to an integer 
float(x) converts x to a floating point number 
complex(real [,imag]) creates a complex number 
str(x) Converts object x to a string 
repr(x) converts object x to expression string 
eval(str) is used to compute a valid Python expression in a string and return an object 
tuple(s) converts sequence s into a tuple 
list(s) Converts sequence s to a list 
chr(x) converts an integer into a character 
unichr(x) Converts an integer to a Unicode character 
ord(x) converts a character to its integer value 
hex(x) converts an integer to a hexadecimal string 
oct(x) converts an integer to an octal string

5.3. Mathematical Functions

abs(x) returns the absolute value of a number, such as abs(-10) returns 10
 ceil(x) returns the upper integer of the number, such as math.ceil(4.1) returns 5
 cmp(x, y) if x < y returns - 1, if x = y returns 0, and if x > y returns 1
 exp(x) returns the x power (ex) of e, such as math.exp(1) returns 2.718281828459045
 fabs(x) returns the absolute value of the number, such as math.fabs(-10) returns 10.0
 floor(x) returns the rounded integer of a number, such as math.floor(4.9) returns 4
 log(x) such as math.log(math.e) returns 1.0,math.log(100,10) returns 2.0
 log10(x) returns the logarithm of x based on 10, such as math.log10(100) returns 2.0
 max(x1, x2,...) returns the maximum value of a given parameter, which can be a sequence.
min(x1, x2,...) returns the minimum value of a given parameter, which can be a sequence.
modf(x) returns the integer and decimal parts of X. The numeric symbols of the two parts are the same as x, and the integer parts are expressed in floating-point form.
The value of the pow(x, y) x**y operation.
round(x [,n]) returns the rounded value of floating-point X. If n is given, it represents the number of digits rounded to the decimal point.
sqrt(x) returns the square root of the number x, the number can be negative, and the return type is real, such as math.sqrt(4) returns 2+0j.

6. List
6.1. Initialization 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 exclude the element with subscript 5.'''
print "nums[2:5]:", nums[2:5]
'''nums[1:]: [3, 5, 7, 8, 13, 20] Cut from subscript 1 to last element'''
print "nums[1:]:", nums[1:]
'''nums[:-3]: [1, 3, 5, 7] Cut from the initial element to the penultimate element, but do not contain 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 nums[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 list pair + sum operator is similar to a string. + Numbers are used for combination lists and numbers are used for repeating lists, for example:

print len([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 2 3

6.6. List interception

L=['spam', 'Spam', 'SPAM!'];
print L[2]; #'SPAM!'
print L[-2]; #'Spam'
print L[1:]; #['Spam', 'SPAM!']

6.7. List function-method

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 in another sequence at the end of the list at once (extend the original list with a new list)
list.index(obj) finds the index location of the first matching item of a value from the list, and the index starts at 0.
list.insert(index, obj) inserts objects into the list
 list.pop(obj=list[-1]) removes an element from the list (default last element) and returns the value of that element
 list.remove(obj) removes the first match of a value in the list
 list.reverse() Inverse list elements, inverted
 list.sort([func]) sorts the original list

7. Tuple

Python tuples are similar to lists, except that elements of tuples cannot be modified; tuples use parentheses (), lists use parentheses []; tuples are created simply by adding elements in parentheses and separating them with commas (,), for example:

tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d";

Create empty tuples, such as tup = ();

When there is only one element in a tuple, you need to add a comma after the element, for example: Tup1 = 50,;

Tuples are similar to strings. Subscript indexes start at 0 and can be intercepted, combined, etc.

7.1. Access tuples

tup1 = ('physics', 'chemistry', 1997, 2000);
#tup1[0]: physics
print "tup1[0]: ", tup1[0]
#tup1[1:5]: ('chemistry', 1997)
print "tup1[1:5]: ", tup1[1:3]

7.2. Modifying tuples
Element values in tuples are not allowed to be modified, but we can join and combine tuples, for example:

tup1 = (12, 34.56);
tup2 = ('abc', 'xyz');

# The following modification of tuple element operations is illegal.
# tup1[0] = 100;

# Create a new tuple

tup3 = tup1 + tup2;
print tup3; #(12, 34.56, 'abc', 'xyz')

7.3. Delete tuples
Element values in tuples are not allowed to be deleted. del statements can be used to delete entire tuples, for example:

tup = ('physics', 'chemistry', 1997, 2000);
print tup;
del tup;

7.4. Tuple Operator
Like strings, tuples can be manipulated using + and * numbers. This means that they can combine and replicate, and a new tuple will be generated after the operation.

7.5. Tuple Index & Interception

L = ('spam', 'Spam', 'SPAM!');
print L[2]; #'SPAM!'
print L[-2]; #'Spam'
print L[1:]; #['Spam', 'SPAM!']

7.6. Tuple built-in functions

cmp(tuple1, tuple2) compares two tuple elements.
len(tuple) calculates the number of tuple elements.
max(tuple) returns the maximum value of the element in the tuple.
min(tuple) returns the minimum value of the element in the tuple.
tuple(seq) converts lists to tuples.

8. Dictionary

8.1. Introduction to Dictionaries
Dictionary is the most flexible built-in data structure type in python besides list. A list is an ordered combination of objects, and a dictionary is an unordered collection of objects. The difference between the two is that the elements in a 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 grammar is as follows:

dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'};

Dictionaries can also be created as follows:

dict1 = { '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 set in braces ({}). Keys must be unique, but values need not be; values can take any data type, but 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. Revising Dictionaries
The way to add new content to dictionaries is to add new key/value pairs and modify or delete existing key/value pairs as follows:

#!/usr/bin/python
dict = {'name': 'Zara', 'age': 7, 'class': 'First'};
dict["age"]=27; #Modify the value of an existing key
dict["school"]="wutong"; #Add new key/value pairs
print "dict['age']: ", dict['age'];
print "dict['school']: ", dict['school'];

8.4. Delete Dictionaries
Deldict ['name']; Delete key is the entry of'name'.
dict.clear(); empty all entries in the dictionary
Deldict; 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. del causes an exception.

8.5. Dictionary Built-in Function-Method

'''
Nobody answered the question? Editor created a Python learning and communication QQ group: 857662006 
Look for like-minded friends, help each other, there are good video learning tutorials and PDF e-books in the group!
'''
cmp(dict1, dict2) compares two dictionary elements.
len(dict) calculates the number of dictionary elements, that is, the total number of keys.
str(dict) outputs a printable string representation of the dictionary.
type(variable) returns the input variable type, and if the variable is a dictionary, it returns the dictionary type.
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 key of the dictionary and val as the initial value corresponding to all the keys in the dictionary.
radiansdict.get(key, default=None) returns the value of the specified key, if the value is not returned in the dictionary
 radiansdict.has_key(key) returns false if the key returns true in dictionary dict
 radiansdict.items() returns a traversable array of (keys, values) tuples in a list
 radiansdict.keys() returns all keys in a dictionary in a list
 radiansdict.setdefault(key, default=None) is similar to get(), but if the key does not already exist in the dictionary, the key will be added and the value set to default.
radiansdict.update(dict2) updates the key / value pairs of dictionary dict2 to Dict
 radiansdict.values() returns all values in the dictionary in a list

9. Date and time

9.1. Get the current time, for example:

import time, datetime;

localtime = time.localtime(time.time())
\#Local current time : time.struct_time(tm_year=2014, tm_mon=3, tm_mday=21, tm_hour=15, tm_min=13, tm_sec=56, tm_wday=4, tm_yday=80, tm_isdst=0)
print "Local current time :", localtime

Description: time.struct_time(tm_year=2014, tm_mon=3, tm_mday=21, tm_hour=15, tm_min=13, tm_sec=56, tm_wday=4, tm_yday=80, tm_isdst=0) belongs to the struct_time tuple. The struct_time tuple has the following attributes:

9.2. Time to get formatting
Various formats can be selected according to requirements, but the simplest function to obtain readable time patterns is asctime():
2.1. Date to String

First choice: print time. strftime ('%Y-%m-%d%H:%M:%S');
Second: print datetime. datetime. strftime (datetime. datetime. now (),'%Y-%m-%d%H:%M:%S')
Finally: print str (datetime. datetime. now ()[: 19]

2.2. String to date

expire_time = "2013-05-21 09:50:35"
d = datetime.datetime.strptime(expire_time,"%Y-%m-%d %H:%M:%S")
print d;

9.3. Date difference of acquisition

oneday = datetime.timedelta(days=1)
#Today, 2014-03-21
today = datetime.date.today()
#Yesterday, 2014-03-20
yesterday = datetime.date.today() - oneday
#Tomorrow, 2014-03-22
tomorrow = datetime.date.today() + oneday
#Get the time for today's zero, 2014-03-21:00:00:00
today_zero_time = datetime.datetime.strftime(today, '%Y-%m-%d %H:%M:%S')

#0:00:00.001000 
print datetime.timedelta(milliseconds=1), #1 millisecond
#0:00:01 
print datetime.timedelta(seconds=1), #One second
#0:01:00 
print datetime.timedelta(minutes=1), #1 minute
#1:00:00 
print datetime.timedelta(hours=1), #One hour
#1 day, 0:00:00 
print datetime.timedelta(days=1), #1 days
#7 days, 0:00:00
print datetime.timedelta(weeks=1)

9.4. Acquisition time difference

#1 day, 0:00:00
oneday = datetime.timedelta(days=1)
#Today, 2014-03-21 16:07:23.943000
today_time = datetime.datetime.now()
#Yesterday, 2014-03-20 16:07:23.943000
yesterday_time = datetime.datetime.now() - oneday
#Tomorrow, 2014-03-22 16:07:23.943000
tomorrow_time = datetime.datetime.now() + oneday
//Note that the time is a floating point number with milliseconds.

//To get the current time, you need to format it:
print datetime.datetime.strftime(today_time, '%Y-%m-%d %H:%M:%S')
print datetime.datetime.strftime(yesterday_time, '%Y-%m-%d %H:%M:%S')
print datetime.datetime.strftime(tomorrow_time, '%Y-%m-%d %H:%M:%S')

9.5. Get the last day of last month

last_month_last_day = datetime.date(datetime.date.today().year,datetime.date.today().month,1)-datetime.timedelta(1)

9.6. The string date is formatted into seconds and returns the floating-point type:

expire_time = "2013-05-21 09:50:35"
d = datetime.datetime.strptime(expire_time,"%Y-%m-%d %H:%M:%S")
time_sec_float = time.mktime(d.timetuple())
print time_sec_float

9.7. The date is formatted into seconds and returns the floating-point type:

d = datetime.date.today()
time_sec_float = time.mktime(d.timetuple())
print time_sec_float

9.8, seconds to string

time_sec = time.time()
print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time_sec))

Posted by harsh00008 on Thu, 15 Aug 2019 07:37:46 -0700