Python data type

Source: Internet
Author: User
Tags delete key mathematical functions shallow copy square root timedelta

Http://www.cnblogs.com/linjiqin/p/3608541.html

1. String
1.1. How to use strings in Python
A, use single quotation marks (')
Enclose a string in single quotation marks, for example:
Str= ' This is string ';
Print str;

b, use double quotation marks (")
The string in double quotes is exactly the same as the string usage in single quotes, for example:
Str= "This is a string";
Print str;

C, use three quotation marks ("')
Use three quotation marks, which represent multiple lines of string, that can be used freely in three quotation marks and double quotation marks, for example:
Str= "This is a string
This is Pythod string
This is a string "
Print str;

2. Boolean type
Bool=false;
print bool;
Bool=true;
print bool;

3, Integer
int=20;
print int;

4. Floating point number
float=2.3;
print float;

5. Digital
Include integers, floating-point numbers.
5.1. Delete numeric object references, for example:
A=1;
d=t;
c=3;
Del A;
del B, C;
#print A; #删除a变量后, calling the A variable again will cause an error.

5.2. Numeric 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) to convert the object x to a string repr (x) to convert the object x to the expression string eval (St R) is used to calculate a valid Python expression in a string and returns an object tuple (s) converts the sequence s to a tuple list (s) converts the sequence s to a list Chr (x) converts an integer to 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 the number, such as ABS (-10) return 10ceil (x) returns    the number of the integer, such as Math.ceil (4.1) returns 5CMP (x, y) if x < y returns-1 if x = = y returns 0, If x > Y returns 1exp (x)    returns the X-Power of E (ex), such as MATH.EXP (1) returns    the absolute value of the 2.718281828459045fabs (x) return number, such as Math.fabs (-10) return 10.0floor (x) returns the number of the lower-rounding integer, such as Math.floor (4.9) return 4log (x)    as Math.log (MATH.E) return 1.0,math.log (100,10) return 2.0log10 (x) Returns the logarithm of x with a base of 10, such as MATH.LOG10 (100) returns 2.0max (x1, x2,...)    Returns the maximum value of a given parameter, which can be a sequence. Min (x1, x2,...)    Returns the minimum value for a given parameter, which can be a sequence. MODF (x)    returns the integer part and fractional part of X, the two-part numeric symbol is the same as x, and the integer part is represented by a floating-point type. Pow (x, y) the value after the x**y operation. Round (x [, N]) returns the rounding value of the floating-point number x, given the n value, which represents the 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. 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 labeled 2 to the element labeled 5, but not containing the element labeled 5 "print" Nums[2:5]: ", Nums[2:5] "nums[1:]: [3, 5, 7, 8, 13, 20] from subscript 1 to the last element ' print ' nums[1:]:", nums[1:] ' nums[:-3]: [1, 3, 5, 7] from the very beginning of the element one Cut straight to the 3rd element, but not 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";p rint nums[0];

6.4. Delete list elements

del Nums[0]; " nums[:]: [3, 5, 7, 8, +] "print" nums[:]: ", nums[:];

6.5. List Script operators
The operands of the list to + and * are similar to strings. The + sign is used for the combined list, and the * number is used for repeating lists, for example:

Print Len ([1, 2, 3]); #3print [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] #Truefor 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 Functions & Methods

List.append (obj) adds a new object at the end of the list list.count (obj) counts the number of occurrences of an element in the list list.extend (SEQ) appends multiple values from another sequence at the end of the list (the original list is expanded with a new list) List.index (obj) finds the index position of the first occurrence of a value from the list, the index starts at 0 list.insert (index, obj) removes an element from the list by inserting the object into the list List.pop (Obj=list[-1]) ( The default last element), and returns the value of the element list.remove (obj) removes the first occurrence of a value in the list List.reverse () reverses the list of elements, reversing List.sort ([func]) to sort the original list

7, tuple (tuple)

Python's tuples are similar to lists, except that the elements of tuples cannot be modified; tuples use parentheses (), and the list uses square brackets []; tuple creation is simple, just add elements in parentheses and separate them with commas (,), for example:

Tup1 = (' Physics ', ' Chemistry ', 1997, n); tup2 = (1, 2, 3, 4, 5); tup3 = "A", "B", "C", "D";

Create an empty tuple, for example: 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, and subscript indexes start at 0 and can be intercepted, combined, and so on.

7.1. Accessing tuples

Tup1 = (' Physics ', ' Chemistry ', 1997, a); #tup1 [0]: Physicsprint "tup1[0]:", tup1[0] #tup1 [1:5]: (' Chemistry ', 1997) PRI NT "Tup1[1:5]:", Tup1[1:3]

7.2. Modifying tuples
element values in tuples are not allowed to be modified, but we can concatenate combinations of 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; # (34.56, ' abc ', ' XYZ ')

7.3. Delete tuples
The element values in the tuple are not allowed to be deleted, and you can use the DEL statement to delete the entire tuple, for example:

Tup = (' Physics ', ' Chemistry ', 1997, a);p rint Tup;del tup;

7.4, tuple operators
As with strings, you can use the + and * numbers to perform operations between tuples. This means that they can be combined and copied, and a new tuple is 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 functions

CMP (Tuple1, tuple2) compares two elements of tuples. Len (tuple) calculates the number of tuple elements. Max (tuple) returns the maximum value of the element in the tuple. MIN (tuple) returns the element minimum value in the tuple. A tuple (SEQ) converts a list to a tuple.

8. Dictionaries

8.1. Introduction to the Dictionary
The Dictionary (dictionary) is the most flexible built-in data structure type in Python, in addition to the list. A list is an ordered combination of objects, and a dictionary is a collection of unordered objects. The difference between the two is that the elements in the dictionary are accessed by keys, not by offsets.

A dictionary consists of a key and a corresponding value. Dictionaries are also referred to as associative arrays or hash tables. The basic syntax is as follows:

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

You can also create a dictionary like this:

Dict1 = {' abc ': 456};d ict2 = {' abc ': 123, 98.6:37};

Each key and value must be separated by a colon (:), each pair is separated by commas, and the whole is placed in curly braces ({}). The key must be unique, but the value is not necessary; The value can take any data type, but it must be immutable, such as a string, a number, or a tuple.

8.2. Access the values in the dictionary

#!/usr/bin/pythondict = {' name ': ' Zara ', ' age ': 7, ' class ': ' First '};p rint ' dict[' name ']: ", dict[' name '];p rint" Dict[' AG E ']: ", dict[' age ');

8.3. Modify the Dictionary
The way to add new content to a dictionary is to add a new key/value pair, modify or delete an existing key/value pair as follows:

#!/usr/bin/pythondict = {' name ': ' Zara ', ' age ': 7, ' class ': ' First '};d ict["age"]=27; #修改已有键的值dict ["School"]= "Wutong"; #增加新的键/value pair print "dict[' age ']:", dict[' age ');p rint "dict[' School ']:", dict[' school '];

8.4. Delete Dictionary
Del dict[' name ']; # Delete key is ' name ' entry
Dict.clear (); # Empty Dictionary all entries
Del Dict; # Delete Dictionary
For example:

#!/usr/bin/pythondict = {' name ': ' Zara ', ' age ': 7, ' class ': ' First '};d el dict[' name '), #dict {' Age ': 7, ' class ': ' First '}PR int "Dict", dict;

Note: The dictionary does not exist, and Del throws an exception

8.5. Dictionary built-in functions & methods

CMP (Dict1, 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 is a printable string representation. Type (variable) returns the type of the variable entered, if the variable is a dictionary. Radiansdict.clear () Removes all the elements in the dictionary radiansdict.copy () returns a dictionary of shallow copy Radiansdict.fromkeys () Creates a new dictionary, with the keys of the elements in the sequence seq as the dictionary, Val is the initial value of the dictionary for all Keys Radiansdict.get (key, Default=none) returns the value of the specified key if the value does not return the default value in the dictionary Radiansdict.has_key (key) Returns Falseradiansdict.items () returns a Dict (key, value) tuple array Radiansdict.keys () in the list if the key returns true in the dictionary. Returns a dictionary with a list of all keys Radiansdict.setdefault (key, Default=none) and get () similar, but if the key does not already exist in the dictionary, The key is added and the value is set to Defaultradiansdict.update (DICT2) to update the key/value pairs of the dictionary dict2 to Dict radiansdict.values () to return all values in the dictionary as 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, t M_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, and the Struct_time tuple has the following properties:

9.2. Get the formatted time
Various formats can be selected on demand, but the simplest function to get a readable time pattern is asctime ():
2.1. Convert date to String

Preferred: Print time.strftime ('%y-%m-%d%h:%m:%s '); second: Print Datetime.datetime.strftime (Datetime.datetime.now (), '%y-%m-%d %h:%m:%s ') Last: Print str (Datetime.datetime.now ()) [: 19]

2.2. String conversion 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. Get Date Difference

Oneday = Datetime.timedelta (Days=1) #今天, 2014-03-21today = Datetime.date.today () #昨天, 2014-03-20yesterday = Datetime.date.today ()-oneday# tomorrow, 2014-03-22tomorrow = Datetime.date.today () + oneday# get today 0 point of time, 2014-03-21 00:00:00today_zero_time = Datetime.datetime.strftime (today, '%y-%m-%d%h:%m:%s ') #0:00:00.001000 Print Datetime.timedelta (Milliseconds=1), #1毫秒 #0:00:01 print Datetime.timedelta (Seconds=1), #1秒 #0:01:00 Print Datetime.timedelta (Minutes=1), #1分钟 #1:00:00 print Datetime.timedelta (Hours=1), #1小时 # Day, 0:00:00 print Datetime.timedelta (Days=1), #1天 # # days, 0:00:00print Datetime.timedelta (Weeks=1)

9.4. Get the time difference

#1 Day, 0:00:00oneday = Datetime.timedelta (Days=1) #今天, 2014-03-21 16:07:23.943000today_time = Datetime.datetime.now () # Yesterday, 2014-03-20 16:07:23.943000yesterday_time = Datetime.datetime.now ()-oneday# tomorrow, 2014-03-22 16:07:23.943000tomorrow _time = Datetime.datetime.now () + oneday note 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 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 as a number of seconds and returns a 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 as a number of seconds, return floating-point type:

D = datetime.date.today () time_sec_float = Time.mktime (D.timetuple ()) Print Time_sec_float

9.8, seconds turn string

Time_sec = Time.time () print time.strftime ("%y-%m-%d%h:%m:%s", Time.localtime (TIME_SEC))

Python data 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.