python data type details

Posted by Qense on Wed, 12 Feb 2020 18:23:36 +0100

python data type classification

1. Numeric types: integer (int), float, Boolean (bool values: True, False)
2). Container type : String (str), list, tuple, dictionary, set
3). Custom types: Person, Animal, Dog, Cat, Student...
NoneType: None

String type (str)

Features: One of the container types that satisfies an ordered (indexed), repeatable, and immutable data type (immutable: refers to the element at a location in the string that is not allowed to change, but the address in the entire string variable can be changed

Variable (meaning that the string is completely overwritten)

1. Display of custom print effects

Use:''...'''or'''...'' to define string data. In some cases, you need to control the display style of the defined character data, you can define string data in the following way to achieve the effect of line break

1 content = "" "Imagine when Gongdu was married!
2) Bold hair, feather towels,
3) Smiles and ashes.
4 content1 ='''Imagine when Gongdu got married!
5) Bold hair, feather towels,
6) Smiles and ashes''
7 print(content) 
8 print(content1)  

2. Escape Characters

Escape character: Remove the original meaning of a character and give it a new meaning
Common escape characters are as follows:
\n: Line break
\t: Tab character
\b: Backspace
\": double quotation marks
\': Single quotation mark
If a string describes a string of physical addresses that may contain escape characters, the parsing of our path can cause errors, so we need to append an r to the first quotation mark in the string to avoid escaping

1 address = "d:\\basic\\tpython1809\\day02\\note.txt"
2 address = r"d:\basic\tpython1809\day02\note.txt"
3 print(address)

3. String * and + operations

String data and string data can be stitched together using the + sign.
Use a * connection between string data and integers to repeat string data multiple times

4. Index of strings

Start index: 0
End index: -1/ length - 1

5. The role of the built-in function len()

For example: len(obj) -->Get len gt h/size/capacity of container object obj

6. How to access string elements

1). Get elements:
Through variable names with Subscripts
2). Setting element:
Since strings are immutable data types, there is no element set

7. Common Runtime Exceptions: IndexError

There is a problem with the following code: Because str1 is 10 in length, it has a maximum index of 9.
Causes code to have an exception of type IndexError because the subscript is out of bounds, which needs to be avoided

8. String slicing

Objective: To get part of the substring data from the original string, and the final substring will not change.
Format: String variable [[start]:[end]:[step]] [Note] Internal brackets indicate optional meaning
Explanation of parameters: start: start: start position; end: end position; step: step (default is 1), which satisfies the feature of heading without tail (99% case) [start,end)

9. Placeholders

When defining string data, it may not be clear what to fill in at some locations, so take up the location first, and wait until the data is determined before filling in
1). Percentage principle:
Symbol:
%d: Integer placeholder
%f: decimal placeholder
%s: Universal Placeholder
2). The principle of braces:
format() in the str class needs to be used to get results

 1 name = "jerry"
 2 age = 18
 3 height = 185.5
 4  
 5 print("Full name:%s,Age:%d,Height:%.1fcm" %("Hanmei",21,163.5))
 6 print("Full name:%s,Age:%010d,Height:%010.1fcm" %(name,age,height))
 7 
 8 print("Favorite singer:{},Favorite movies:{},Favorite games to play:{},Favorite programming language:{}".format("Jacky Cheung","dominant sea power","World of Warcraft","python"))
 9 print("Favorite singer:{3},Favorite movies:{1},Favorite games to play:{2},Favorite programming language:{0}".format("java","Spider-Man","LOL","Jay Chou"))
10 print("Favorite teacher:{teacher},Favorite movies:{film},Favorite games to play:{game},Favorite programming language:{language}".format(language="js",
11        teacher="Micro Sister",film="skin flick",game="Super Marie"))

10. Common functions in strings

'sep'.join(seq): the SEP separator can be empty; the element sequence, string, tuple, Dictionary of the SEQ connection

[Supplement] os.path.join(): Return after combining multiple paths

2). ljust(width,format): Display str data on the left, if the length/size does not exceed width, then complement format on the right

3). rjust(width,format): Display str data on the right, if the length/size does not exceed width, then complement format on the left

4). center(width,format): Display str data in the middle, if the length/size does not exceed width, then complement the format on the left and right

5). zfill(width): Display str data on the right, if the length/size does not match the width, then add 0 to the left

6). strip(): Removes the matched character data on the left and right sides of the string and returns a new string

7). lstrip(): Removes the character data matched to the left of the string and returns a new string

8). rstrip(): Removes the character data matched to the right of the string and returns a new string

9). replace(old,new,[number]): replace old content in str with new, default to replace all; optionally replace numbered times

10). split(format): Cuts str in format and returns a list object; what split() of the default empty parameter can cut: '', \n, \t

11). index(s): Returns the corresponding subscript/index of the string s in the original string, returns the first successful match if there is more than one identical data, and errors if none of the matches succeeds

12). count(s): Returns the number of times the string s appears in the original string, and if it does not appear at one time, returns 0

13). find(format): Finds the location of the format that first appears in the string

14). rfind(format): Finds the location of the last format in the string

15). upper(): Change string data to full uppercase

16).lower(): Change string data to all lowercase

17).capitalize(): capitalize the first letter of the string data and lower case the rest

18). title(): capitalize the first letter of the string data and lower case the rest of the letters Note: If there are multiple words, the first letter of each word should be considered

19). swapcase(): Change uppercase to lowercase and lowercase to uppercase in a string

20). startswith(format): Determines whether a string begins with format, and the result of the function is a Boolean value

21). endswith(): Determines whether a string ends with format and the result of the function is a Boolean value

22). isalnum(): Determines if the contents of the string are all English, numeric characters; if so, returns True; otherwise, returns False

23). isalpha(): Determines whether the contents of the string are all English characters; if so, returns True; otherwise, returns False

24). isdecimal(): Determines whether the contents of a string are all numeric characters; if so, returns True; otherwise, returns False

25). isdigit(): Determines whether the contents of a string are all numeric characters; if so, returns True; otherwise, returns False

26). islower(): Determines whether the English and Chinese characters in the string are all lowercase; if so, returns True; otherwise, returns False [Note] Numbers and other characters do not affect

27). isupper(): Determines whether the English and Chinese characters in the string are all capitalized; if so, returns True; otherwise, returns False [Note] Numbers and other characters do not affect

28). istitle(): Determines if the first letter of an English substring (multiple groups) in the string content is capitalized

 1 lt = ['i','love','you','very','much']
 2 print('-'.join(lt))
 3 print(str.join('#',lt))
 4 
 5 str1 = 'i love you very much'        
 6 print(str1.ljust(50,'*'))              #i love you very much******************************
 7 print(str1.rjust(50,'-'))              #------------------------------i love you very much
 8 print(str.rjust(str1,50,'$'))          #$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$i love you very much
 9 print(str1.center(50,'^'))             #^^^^^^^^^^^^^^^i love you very much^^^^^^^^^^^^^^^
10 print(str1.zfill(50))                  #000000000000000000000000000000i love you very much
11 
12 str1 = '  ,,,..\    i hate you very much   ...,,;;\  '
13 print(str1.lstrip('\ ,.'))           #i hate you very much   ...,,;;\  
14 print(str1.rstrip('\;., '))          #,,,..\    i hate you very much
15 print(str1.strip(',\;. '))           #i hate you very much
16 
17 str1 = "python ah python,You are my pride! python ah python,I'm proud of you!"
18 print(str1.replace('python','java'))            #java ah java,You are my pride! java ah java,I'm proud of you!
19 print(str1.replace('python','java',2))          #java ah java,You are my pride! python ah python,I'm proud of you!
20 
21 str1 = 'i love\nabc you\t very\n much'
22 print(str1.split(' '))          #['i', 'love\nabc', 'you\t', 'very\n', 'much']
23 print(str1.split())             #['i', 'love', 'abc', 'you', 'very', 'much']
24 print(str1.split('\n'))         #['i love', 'abc you\t very', ' much']
25 print(str1.splitlines())        #['i love', 'abc you\t very', ' much']
26 
27 str1 = 'abcdefgd1234567'
28 print(str1.index('d'))     #3
29 print(str1.index('efg'))   #4
30 print(str1.index('xyz'))   #Report errors
31 
32 str1 = 'dsaalkfaaasdfaaaa2141aaaaaaxyz'
33 print(str1.count('a'))     #15
34 print(str1.count('aa'))    #7
35 print(str1.count('www'))   #0
36 
37 str1 = 'Mountain is not high, fairy is spiritual; water is not deep, dragon is spiritual; S is in the shadows, I only love'
38 print(str1.find('In'))        #2
39 print(str1.rfind('In'))       #24
40 
41 str1 = 'today is thursday PM'
42 print(str1.upper())          #TODAY IS THURSDAY PM
43 print(str1.lower())          #today is thursday pm
44 print(str1.capitalize())     #Today is thursday pm
45 print(str1.title())          #Today Is Thursday Pm
46 print(str1.swapcase())       #TODAY IS THURSDAY pm
47 
48 str1 = 'hahaha abcdefghijk 32141234 hehehe'
49 print(str1.startswith('h'))         #True
50 print(str1.startswith('ha'))        #True
51 print(str1.startswith('haha'))      #True
52 print(str1.startswith('Haha'))      #False
53 print(str1.startswith('hahha'))     #False
54 
55 print(str1.endswith('e'))           #True
56 print(str1.endswith('he'))          #True
57 print(str1.endswith('ehe'))         #True
58 print(str1.endswith('Hehe'))        #False
59 
60 str1 = '3214Love&Tdsajflks*^'
61 print(str1.isalnum())          #False
62 print(str1.isalpha())          #False
63 print(str1.isdigit())          #False
64 print(str1.isdecimal())        #False
65 print(str1.islower())          #False
66 print(str1.isupper())          #False
67 print(str1.istitle())          #Ture

List type

Features: Ordered (indexed, defined, and displayed in the same order), variable (can change element content or automatically (expanded) content), repeatable, and can store elements of any data type

1. How to access elements in a list

1). Get Elements
List names obtained with subscripts-->For example: lt[0],lt[-1]
2). Setting elements (different from str)
List name with subscript=... --> For example: lt[4] = "Wu Da Lang"

2. List + and * operations

For the + operation, combine elements from both list objects and return them as a new list
For * operations: repeat elements in a list n times, return with a new list

3. Some functions related to lists

append(obj): Append obj elements to the end of the list
clear(): empty the list, the element is gone, the list object is still: lt.clear()

4.del keyword is used with list objects/elements

Purpose: Recycle list objects, and reclaim the contents of the elements (that is, reclaim list objects or reclaim list elements):del lt
Del deletes the element at the specified location in the list: del lt[1]

 

5. Slicing of lists

The format is identical to str...

1 lt6 = ['Cucurbita dolls','Sheriff Black Cat','Bears abound','Slamdunk','Conan','Haier brothers']
2 lt7 = lt6[1:5]
3 print(lt7,type(lt7))
4 print(lt6,type(lt6))
5 print(lt6[2:-2])
6 print(lt6[:])
7 print(lt6[::-1])

6. Definition format of summary list

Format 1: List name = [Value 1, Value 2,..., Value n]
Format 2: List name = [Variable 1, Variable 2,..., Variable n] = [Value 1, Value 2,..., Value n]
Format 3: List name = []

7. Common functions in lists

1). append(obj): Save obj to the last place in the list

2). extend(iterable): Remove each element from the Iterable object to the last place in the list

3).index(obj): Returns the index position where obj appears in the list; if there are multiple identical obj elements, the index of the first occurrence of that element is returned; if one does not, a direct error is reported

4). count(obj): Returns the number of times obj appears in the list; if it does not appear at one time, returns 0

5). pop([index]): If pop() is an empty parameter, eject the last element of the list (as a return value to the program); if there is a parameter, it must be an index value, eject the element at the specific index position

6). remove(element): delete an element that matches an element without returning a value; if there are multiple matches, delete only the first one

7). reverse(): Reverse list elements

Sort ([reverse=True], [key=...]): defaults to ascending (reverse=False), if you want to descend, display the definition reverse=True

 1 lt = ['Monkey D Luffy','Solo','Yamagata','Name','Usop','Joba','Brooke']
 2 lt.append('Shanks')
 3 print(lt)   # ['Monkey D Luffy','Solo','Yamagata','Name','Usop','Joba','Brooke','Shanks']
 4 lt.append(['Kakashi','Narrator','Assistance','Cherry'])
 5 print(lt)   # ['Monkey D Luffy','Solo','Yamagata','Name','Usop','Joba','Brooke','Shanks',['Kakashi','Narrator','Assistance','Cherry']]
 6 
 7 lt = ['Monkey D Luffy','Solo','Yamagata','Name']
 8 lt.extend(['Kakashi','Narrator','Assistance','Cherry'])      # ['Monkey D Luffy', 'Solo', 'Yamagata', 'Name','Kakashi', 'Narrator', 'Assistance', 'Cherry']
 9 lt.extend('Da She Wan')
10 print(lt)            # ['Monkey D Luffy', 'Solo', 'Yamagata', 'Name', 'Kakashi', 'Narrator', 'Assistance', 'Cherry', 'large', 'snake', 'pill']
11 lt.extend(200)       # TypeError: 'int' object is not iterable
12 
13 lt = ['Monkey D Luffy','Solo','Yamagata','Name','Usop','Joba','Brooke','Name']
14 print(lt.index('Name'))       # 3
15 # print(lt.index('Name1'))    # Error ValueError
16 
17 print(lt.count('Monkey D Luffy'))       #1
18 print(lt.count('Name'))       #2
19 print(lt.count('Name1'))      #0
20 
21 print(lt.pop())      #Name
22 print(lt)            #['Monkey D Luffy','Solo','Yamagata','Name','Usop','Joba','Brooke']
23 print(lt.pop(1))     # Solo
24 print(lt)            #['Monkey D Luffy', 'Yamagata', 'Name', 'Usop', 'Joba', 'Brooke']
25 # lt.pop('Joba')    # Illegal operation with error
26 
27 lt = ['Monkey D Luffy','Solo','Yamagata','Name','Usop','Joba','Brooke','Name']
28 print(lt.remove('Yamagata'))  # None
29 print(lt)    #['Monkey D Luffy','Solo','Name','Usop','Joba','Brooke','Name']
30 lt.remove('Name')
31 print(lt)    #['Monkey D Luffy','Solo','Usop','Joba','Brooke','Name']
32 
33 print(lt.clear())   #None
34 print(lt)      #[]
35 
36 lt = ['Monkey D Luffy','Solo','Yamagata','Name','Usop','Joba','Brooke','Name']
37 lt.reverse()
38 print(lt)       #obtain['Name','Brooke','Joba','Usop','Name','Yamagata','Solo','Monkey D Luffy']
39 
40 lt1 = [53,23,-17,9,-21,0,79,88,-30]
41 lt1.sort()
42 print(lt1)    #[-30, -21, -17, 0, 9, 23, 53, 79, 88]
43 lt1.sort(reverse=True)
44 print(lt1)    #[88, 79, 53, 23, 9, 0, -17, -21, -30]

3. Tuple

Features: Ordered (indexed, defined, and displayed in the same order), immutable (as understood by str), repeatable, elements that can store any data type

1. How to access elements in a meta-ancestor

1). Get Elements
Ancestor name obtained with subscript--> For example: tp[0],tp[-1]
2). Setting elements (consistent with str)
Without this operation, it is illegal because meta-ancestors are immutable data types

2. Meta-ancestor's + and *operations

For the + operation, the elements in both meta-ancestor objects are grouped together and returned as a new meta-ancestor
For * operations, repeat elements in a meta-ancestor n times and return with a new meta-ancestor
[Note] Does the meta-ancestor have append or clear functions like lists, because append and clear functions change the content of elements inside container objects, which conflicts with immutability

3. The del keyword is used with meta-ancestor objects

Purpose: Recycle the entire meta-ancestor object, but cannot reclaim any of its elements for a tuple type

4. Ancestor's slicing operation

The format is identical to str...

5. Summarize the definition format of meta-ancestors

Format 1: Meta-ancestor name = (value 1, value 2,..., value n)
Format 2: Meta-ancestor name = (variable 1, variable 2,..., variable n) = (value 1, value 2,..., value n)
Format 3: Meta-ancestor name = ()
Format 4: Meta-ancestor name = (value 1,)[Note]: Define meta-ancestor and have only one element, must be displayed with a comma after the element

4. Dictionary Type (dict)

Features: Disorderliness (no index, values are found by keys), variable data types (values are variable, keys are not changeable); the structure of a dictionary is a combination of key-value pairs--> key-value objects; keys: uniqueness (not duplicated), immutable data types (for example, list cannot be used as a key); values: no requirements, can be any type of data, or even duplicate

1. How to access dictionary elements

1). Get value: Dictionary name with key name can get corresponding value

1 dic1 = {"name":"Hanmei","age":23,"height":165.0}
2 dic1['name']           # Hanmei

2). Set value: Dictionary name with key name =...

[Important] 1. If a duplicate key appears when defining a dictionary object, keep the key name while overwriting the previous value.2. In the process of adding a new key-value pair, if the key is not present in the original dictionary object, then the key-value pair is added together and called an element.

1 dic2 = {"name":"Hanmei","age":23,"height":165.0,"name":"Li Lei"}
2 dic2['weight'] = 120
3 print(dic2)

2. Dictionary-related functions

clear(): empty dictionary elements, keep empty dictionary objects, dic2.clear()

3. Use with keyword del

Purpose: Recycle key-value pair combinations, or entire dictionary objects; del dic2['age'] #Delete age key pairs; del dic2 #Delete all (data and entire dictionary structure)

4. Finding values by keys

Mode 1: Dictionary name [key name] Error if key does not exist; KeyError type exception; dic2["name1"]
Mode 2: Dictionary name.get (key name) If the key does not exist, it will not error and return a None value to the program; this method is safe/friendly (better); dic2.get("name1")

[Important] Key: Must satisfy the immutable data type; Enumeration: int, float, bool, str, None and so on can act as the key to satisfy uniqueness (not repeatable); Value: no requirement, any type can, or even repeatable.

5. Functions commonly used in dicts

1). dic1.update(dic2): Compare each key-value pair in dic2 with that in dic1. If the same key exists in dic1, the key is guaranteed to remain unchanged and the value is overwritten. If there is no corresponding key-value pair in dic1, add it to dic1

items(): Returns an object of type dict_items encapsulated with a meta-ancestor acting as its element and containing two pieces of key and value

keys(): Returns an object of type dict_keys, encapsulating the keyset internally

values(): Returns an object of type dict_values encapsulated with a set of values

popitem(): ejects the last key-value pair and returns it as a meta-ancestor

pop(key): When a key is passed in, the entire key-value pair is popped up and returned to the program value.

copy(): copy; dict1.copy()

 1 dic1 = {"name":"Zhang Sanfen","age":120,"height":168.0}
 2 dic2 = {"name":"Golden Lion","weight":100,"faceValue":False,"girlFriend":"Extinction division too"}
 3 dic1.update(dic2)
 4 print(dic1)     #obtain{'name': 'Golden King', 'age': 120, 'height': 168.0, 'weight': 100, 'faceValue': False, 'girlFriend': 'Extinction division too'}
 5 print(dic2)     #obtain{'name': 'Golden King', 'weight': 100, 'faceValue': False, 'girlFriend': 'Extinction division too'}
 6 
 7 dic1 = {"name":"Zhang Sanfen","age":120,"height":168.0}
 8 print(dic1.items(),type(dic1.items()))     #obtain dict_items([('name', 'Zhang Sanfen'), ('age', 120), ('height', 168.0)]) <class 'dict_items'>
 9 print(dic1.keys(),type(dic1.keys()))       #obtain dict_keys(['name', 'age', 'height']) <class 'dict_keys'>
10 print(dic1.values(),type(dic1.values()))   #obtain dict_values(['Zhang Sanfen', 120, 168.0]) <class 'dict_values'>
11 
12 dic2 = {"name":"Golden Lion","weight":100,"faceValue":False,"girlFriend":"Extinction division too"}
13 print(dic2.popitem())          #('girlFriend', 'Extinction division too')
14 print(dic2)                    #{'name': 'Golden King', 'weight': 100, 'faceValue': False}
15 print(dic2.pop('weight'))      #100
16 print(dic2)                    #{'name': 'Golden King', 'faceValue': False}       
17 
18 dic3 = dic2.copy()     # id change
19 print(dic2,id(dic2))   #obtain{'name': 'Golden King', 'weight': 100, 'faceValue': False, 'girlFriend': 'Extinction division too'} 5999280
20 print(dic3,id(dic3))   #obtain{'name': 'Golden King', 'weight': 100, 'faceValue': False, 'girlFriend': 'Extinction division too'} 5999352

Set Type

Features: Unordered (no index, every time the effect is different), unique (not repeatable), variable, can only store immutable data.Scenarios for use: Frequently used for data de-weighting (filtering) during actual development

1. Some common operations for collections are as follows

The following actions are used in both collection objects
Symbol:
&: Take Intersection
|: Union
-: Difference set (for the operation of difference set, you need to focus on who is in front of the - sign (left), and who is returning unique data)
^: Union before discarding intersection

[Note] There is no + operation between a set and a set.TypeError type error will occur

2. Set-related functions

clear(): Empty the collection, keep the shell

3. Use with keyword del

Purpose: Recycle collection elements or entire collection objects

1 s1 = {"army officer's hat ornaments","Xishi","Wang Zhaojun","the moon"}
2 s1.clear()
3 print(s1)      # set()
4 del s1
5 print(s1)      # Directly deleted,Nothing left,So error NameError:name's1'is not defined

Think: What should I do to delete the mink cicada data?

1). Can be achieved by using the remove(obj) function; 2). First convert the set to a list --> use the conversion function list(), then use the idea of loops to process the list objects, once the "mink cicada" is matched, the del keyword can be used to delete the data.

 1 # Method 1
 2 s1.remove("army officer's hat ornaments")
 3 
 4 # Method 2
 5 lt = list(s1)   # Convert Collection to List
 6 i = 0
 7 while i < len(lt):
 8     if lt[i] == "army officer's hat ornaments":
 9         print(lt[i])
10         del lt[i]
11     i += 1
12 print(lt)

4. Define an empty set

s1 = set( )

5. Functions commonly used in set

1). add(e): Add an element E (an immutable data type) to the collection

2). pop(): can only be an empty parameter (set has no concept of index), randomly pop up an element from the set

3). remove(e): delete elements matching e from the collection

4).clear(): Empty the collection, keep the container

5).copy(): copy

6).issubset(s): Determines whether a set is a subset of another set; s1.issubset (s2) > > S1 is a subset of S2

7). issuperset(s): Determines whether a set is the parent of another set; s1.issubset (s2) > > S1 is the parent of S2

8). isdisjoint(s): Determines whether an intersection exists between two sets, returns False if it exists, and returns True if it does not.

 1 s1 = {10,100,3.14,"abcd"}
 2 s2 = {3.141,100}
 3 s1.add('hello')
 4 print(s1.pop())
 5 s1.remove(100)
 6 s1.clear()
 7 print(s1)     #set()
 8 print(s1.issubset(s2))    #False
 9 print(s1.issuperset(s2))  #True
10 print(s1.isdisjoint(s2))  #False
11 print(s2.isdisjoint(s1))  #False

Topics: Python Java Programming REST