Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Detailed introduction of data types in Python

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly explains the "detailed introduction of data types in Python". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "detailed introduction of data types in Python".

Catalogue

1. String

2. Boolean type

3. Integer

4. Floating point number

5. Figures

6. List

7. Tuple

8. Dictionary

9. Date

1. String (http://www.cnblogs.com/yjd_hycf_space/p/6846284.html)

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 (")

Strings in double quotes are used exactly the same as strings in single quotes, for example:

Str= "this is string"

Print str

C. Use three quotation marks ('')

Using three quotes to represent multiple lines of a string, you can freely use single and double quotes in the three quotes, 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. Integer

Int=20

Print int

4. Floating point number

Float=2.3

Print float

5. Figures

Including integers, floating-point numbers.

5.1. Delete digital object references, for example:

Axi1

Bread2

Cedar 3

Del a

Del b, c

# print a; # after deleting variable a, calling variable a will report 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 str (x) converts object x to a string repr (x) converts object x to an expression string eval (str) to evaluate a valid Python expression in a string And return an object tuple (s) to convert sequence s to a tuple list (s), convert sequence s to a list chr (x), convert an integer to a character unichr (x), convert an integer to Unicode character ord (x), convert a character to its integer value hex (x), convert an integer to a hexadecimal string oct (x), convert a Convert an integer to an octal string

5.3. Mathematical function

Abs (x) returns the absolute value of the number, for example, abs (- 10) returns the upper integer of the number returned by 10ceil (x), for example, math.ceil (4.1) returns 5cmp (x, y) if x

< y 返回 -1, 如果 x == y 返回 0, 如果 x >

Y returns 1exp (x) returns the x power (ex) of e, for example, math.exp (1) returns the absolute value of 2.718281828459045fabs (x) returns the absolute value of the number, such as math.fabs (- 10) returns the rounded integer of the number returned by 10.0floor (x) For example, math.floor (4.9) returns 4log (x), such as math.log (math.e) returns 1.0 math.log (100jue 10) returns 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 of a given parameter, which can be a sequence. Modf (x) returns the integer part and the decimal part of x, the numerical symbols of both parts are the same as x, and the integer part is represented as a floating point. The value of the pow (x, y) xroomy operation. Round (x [, n]) returns the rounded value of the floating point number x, which, if given, 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, for example, math.sqrt (4) returns 2n0j

6. List

6.1. Initialization list, for example:

List= ['physics',' chemistry', 1997, 2000]

Nums= [1, 3, 5, 7, 8, 13, 20]

6.2. The values in the access 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 does not include the element''print' 'nums [2:5]: ", nums [2:5]' 'nums [1:]: [3, 5, 7, 8, 13, 20] cut from subscript 1 to the last element' 'print" nums [1:]: ", Num [1:]' 'nums [:-3]: [1, 3, 5, 7] cut from the beginning to the penultimate element But does not include 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 operator

The operators of list pairs + and * are similar to strings. The + sign is used to combine lists, and the * sign is used to repeat lists, for example:

Print len ([1, 2, 3]); # 3print [1, 2, 3] + [4, 5, 6]; # [1, 2, 3, 4, 5, 6] print ['hippie'] * 4; # [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 function & method

List.append (obj) add a new object list.count (obj) to the end of the list to count 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 (extend the original list with the new list) list.index (obj) finds the index position of the first match of a value from the list 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 () reverse list, reversing list.sort ([func]) to sort the original list

7. Tuple (tuple)

Tuples in Python are similar to lists, except that the elements of tuples cannot be modified; tuples use parentheses () and lists use square brackets []; tuples are created simply by adding elements in parentheses and separated by commas (,), for example:

Tup1 = ('physics',' chemistry', 1997, 2000); 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 the tuple, you need to add a comma after the element, for example: tup1 = (50,)

Tuples are similar to strings, with subscript indexes starting at 0 and can be intercepted, combined, and so on.

7.1. Access tuple

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

7.2. Modify tuple

Element values in tuples are not allowed to be modified, but we can join and combine tuples, such as:

Tup1 = (12,34.56)

Tup2 = ('abc',' xyz')

The following operations to modify tuple elements are illegal.

# tup1 [0] = 100

# create a new tuple

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

7.3. Delete tuple

Element values in tuples are not allowed to be deleted, and you can use the de statement to delete the entire tuple, for example:

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

7.4. Tuple operator

Like strings, tuples can be operated with the + sign and the * sign. This means that they can be combined and copied, and a new tuple will be generated after the operation.

7.5. Tuple indexing & 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) counts 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 the list to a tuple.

8. Dictionary

8.1. Introduction to dictionaries

Dictionaries (dictionary) are the most flexible built-in data structure types in python besides lists. Lists are ordered combinations of objects, and dictionaries are unordered collections of objects. The difference between the two is that the elements in the dictionary are accessed by keys, not by offsets.

The dictionary consists of keys and corresponding values. Dictionaries are also called 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}; dict2 = {' abc': 123,98.6: 37}

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

8.2. Access the values in the dictionary

#! / usr/bin/pythondict = {'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 the following examples of existing key / value pairs:

#! / usr/bin/pythondict = {'name':' Zara', 'age': 7,' class': 'First'}; dict ["age"] = 27; # modify the value of an existing key dict ["school"] = "wutong"; # add a new key / value pair print "dict [' age']:", dict ['age']; print "dict [' school']:", dict ['school']

8.4. Delete a dictionary

Del dict ['name']; # Delete key is an entry for' name'

Dict.clear (); # clear all dictionary entries

Del dict; # Delete a dictionary

For example:

#! / usr/bin/pythondict = {'name':' Zara', 'age': 7,' class': 'First'}; del dict [' name']; # dict {'age': 7,' class': 'First'} print "dict", dict

Note: dictionary does not exist, del will throw an exception

8.5. Dictionary built-in function & method

Cmp (dict1, dict2) compares two dictionary elements. Len (dict) counts 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, or the dictionary type if the variable is a dictionary. Radiansdict.clear () deletes all elements in the dictionary radiansdict.copy () returns a dictionary shallow copy radiansdict.fromkeys () creates a new dictionary, using the elements in the sequence seq as the dictionary keys, and val returns the specified key value for the initial value radiansdict.get (key, default=None) corresponding to all the keys in the dictionary, if the value does not return the default value radiansdict.has _ key (key) if the key returns true in the dictionary dict Otherwise, return falseradiansdict.items () to return traverable (key, value) tuple array radiansdict.keys () to return a list to return a dictionary all keys 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 will be set to defaultradiansdict.update (dict2) update the key / value pair of the dictionary dict2 to dict radiansdict.values () to return all the values in the dictionary

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

Note: 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 attributes:

9.2. Get the formatting time

You can choose various formats according to your needs, but the easiest function to get a readable time pattern is asctime ():

2.1. Convert the date to a string

First choice: print time.strftime ('% Y-%m-%d% HRV% MRV% S'); secondly: print datetime.datetime.strftime (datetime.datetime.now (),'% Y-%m-%d% HV% MV% S') finally: 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 the date difference

Oneday = datetime.timedelta (days=1) # Today, 2014-03-21today = datetime.date.today () # yesterday, 2014-03-20yesterday = datetime.date.today ()-oneday# tomorrow, 2014-03-22tomorrow = datetime.date.today () + oneday# get today's zero time 2014-03-21 00:00:00today_zero_time = datetime.datetime.strftime (today,'% Y-%m-%d% Hpurs% MGV% S') # 0VOVO 00VIE00.001000 print datetime.timedelta (milliseconds=1), # 1ms # 0:00:01 print datetime.timedelta (seconds=1), # 1s # 0:01:00 print datetime.timedelta (minutes=1), # 1min # 1:00:00 print datetime.timedelta (hours=1), # 1hr # 1 day 0:00:00print datetime.timedelta (days=1), # 1 day # 7 days, 0:00:00print datetime.timedelta (weeks=1)

9.4. Get the time difference

# 1 day, 0:00:00oneday = datetime.timedelta (days=1) # Today, 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 floating point, with milliseconds. Then to get the current time, you need to format it: print datetime.datetime.strftime (today_time,'% Y-%m-%d% HRV% MRV% S') print datetime.datetime.strftime (yesterday_time,'% Y-%m-%d% HRV% MVR% S') print datetime.datetime.strftime (tomorrow_time,'% Y-%m-%d% HRV% MVR% 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 as the number of seconds and the floating point type is returned:

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 seconds and a floating point type is returned:

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

9.8. Convert seconds to string

Time_sec = time.time () print time.strftime ("% Y-%m-%d% H:%M:%S", time.localtime (time_sec)) Thank you for your reading, the above is the content of "detailed introduction of data types in Python". After the study of this article, I believe you have a deeper understanding of the detailed introduction of data types in Python, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report