python data type

python data type

1, Numerical type

2, Character type

3, Container data type


Numerical type

1. Integer

x = 3
x = 5

# id(): Returns an integer representing the address of the variable in memory
# Above two id The returned values are obviously different, indicating that the addresses of variable values are different

2. Floating point type

Floating point numbers are used to deal with real numbers, that is, numbers with decimals. Similar to the double type in C language

Note:   The value range and precision of floating-point numbers are generally unlimited, but there may be errors in floating-point operation, that is, there may be uncertain mantissa

x = 2.23
d = 4.3
c = d-x

3. Boolean

Boolean data type, abbreviated as boolean type, is represented by 'bool' in Python. Bool class is a subclass of int class. Boolean types provide two Boolean values to represent True (True) or False (False). In Python, they are represented by 'True' (True or True) or 'False' (False or False) respectively.

print(True)  # True Capitalize the first letter
print(False)  # False Capitalize the first letter
print(type(True))  # see True Type of
print(type(False))  # see False Type of


<class 'bool'>
<class 'bool'>


1. Representation of string

(1) The symbol series enclosed in single quotation marks, double quotation marks or three quotation marks are called strings, and single quotation marks, double quotation marks, three single quotation marks and three double quotation marks can be nested with each other to represent complex strings

1 "wyb", 'Hello, World', "python", '''Tom said, "Let's go"'''All strings

(2) Empty strings are represented as' ',' '

1 # The following is an empty string:
2 msg = ''
3 name = ""

(3) The string represented by three quotation marks can be wrapped, which supports strings with complex typesetting; Three quotation marks can also represent long comments in the program

1 msg = '''
2 Who am I?
3 Where am i?
4 What am I doing
5 '''
6 print(msg)  # String wrap
1 '''
2 Multiple lines of comments can be written in three quotation marks
3 You can write multiple lines of comments here
4 '''

(4) An unquoted string is considered a variable by the system

>>> name = jack
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'jack' is not defined
>>> jack = "wyb"
>>> name = jack
>>> name

String common methods

(1) String splicing:

+:   Add two strings directly    *: String copied multiple times

join(seq) uses the specified string as the separator to merge all elements (string representation) in seq into a new string

1 >>> name = "wyb"
2 >>> age = "21"
3 >>> name + age
4 'wyb21'
5 >>> name*3
6 'wybwybwyb'
1 >>>''.join("python")
2 'python'
3 >>>'123'.join("python")
4 'p123y123t123h123o123n'

Note: string can only be spliced with string, not with other data types!

1 >>> name = "wyb"
2 >>> age = 21
3 >>> name + age
4 Traceback (most recent call last):
5   File "<stdin>", line 1, in <module>
6 TypeError: must be str, not int

(2) Case:

capitalize() converts the first character of a string to uppercase

swapcase() converts uppercase to lowercase and lowercase to uppercase in the string

upper() converts all lowercase letters in the string to uppercase  

lower() converts all uppercase characters in the string to lowercase

title() returns a "captioned" string, which means that all words start with uppercase and the rest are lowercase

>>> s = "python web framework"
>>> s.capitalize()
'Python web framework'
>>> s
'python web framework'
>>> s.upper()
>>> s.lower()
'python web framework'
>>> s.title()
'Python Web Framework'

>>> s = "ABCDefg"
>>> s.swapcase()

(3) String fill:

center(width, fillchar) returns a string centered on the specified width. Fillchar is a filled character, and the default is a space

ljust(width[, fillchar]) returns a left aligned original string, and uses fillchar to fill in a new string of length width. Fillchar defaults to space.

rjust(width,[, fillchar]) returns a right aligned original string and fills the new string with fillchar (default space) to the length width

zfill (width) returns a string with a length of width. The original string is right aligned and filled with 0

>>> s = "python"
>>>, '*')
>>> s.ljust(10, '*')
>>> s.rjust(10, '*')
>>> s.zfill(10)

(4)numerical calculation:

len(string) Return string length

count(str, beg= 0,end=len(string)) return str stay string The number of times it appears, if beg perhaps end If specified, the specified range is returned str Number of occurrences, str It can be one character or multiple characters

>>> s = "python"
>>> len(s)
>>> s = "111222abcdefga"
>>> s.count(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: must be str, not int
>>> s.count('1')
>>> s.count('1111')
>>> s.count('111')
>>> s.count('a')

Container data type


# append()  Add parameters to the list as elements
a = [1, 2]
a.append([3, 4])    
print(a)    # [1, 2, [3, 4]]
# extend()  Add the parameter list to the list one by one
a = [1, 2]
a.extend([3, 4])
print(a)    # [1, 2, 3, 4]
# insert(index, object)     At the specified location index Insert element before object
a = [1, 2, 3, 4]
a.insert(1, [3, 4])
print(a)    # [1, [3, 4], 2, 3, 4]
Copy code
# There are two methods to modify elements, one is through subscript, and the other is through slice (slice is left closed and right open interval)
a = [1, 2, 3, 4]
# Method 1: subscript modification
a[1] = "in"
print(a)    # [1, 'in', 3, 4]
# Method 2: slice modification,You can also delete
a[2:3] = ["day", "lower", "large", "with"]   # [1, 'in', 'day', 'lower', 'large', 'with', 4]
a[2:3] = []
print(a)    # [1, 'in', 'lower', 'large', 'with', 4]
Copy code
# a.index(x,begin,.end)       # Find the subscript of the character x between begin and end in a. no error will be reported
a = [1, 2, 3]
print(a.index(2))   # 1
Copy code
 list.count(x, begin, end)    # query x Number of in the list
del list[Subscript value]             # Delete by subscript
list.pop()                   # Delete last element,You can also delete the specified subscript, and the deleted content will be returned
list.remove(element)            # Removes the specified element from the list
list.sort(reverse=True)      # sort The method is to rearrange the list in a specific order. The default is from small to large, and the parameter is reverse=True It can be changed to reverse order, from large to small.
list.reverse()                # reverse The way is to list Reverse.


 The dictionary is represented as dict,Use key value pairs to store data. Use curly braces({})To encapsulate these key value pairs, and they are stored in disorder list Generally speaking, the query speed of the dictionary is fast and will not follow key But it needs a lot of memory key The algorithm for calculating location is called hash algorithm.

As follows:

Note: the key can use tuples, numbers and strings. If it is a Boolean value, it will be ignored. If it is a dictionary or list, it will directly report an error.

If the key is repeated, only the last one is retained

Common dictionary methods

# You can use the key to get the dictionary value. If you write a key that is not in the dictionary, an error will be reported. It is generally used get If there is no corresponding key, it will return None,get The second parameter of can set the returned value
a = {"name": "Zhang San", "age": 18, "sex": "male"}
print(a["name"])    # Zhang San
print(a.get("name"))    # Zhang San
print(a.get("nam"))     # None
print(a.get("nam", "can't find"))      # can't find
print(a["nam"])     # report errors
Copy code
# Add a key value pair and directly use: dictionary name["Key name"] = value
a = {"name": "Zhang San", "age": 18, "sex": "male"}
a["address"] = "Beijing"
Copy code
# Dictionary name.keys() Return to all dictionaries key,And put it in a similar list dict_keys In class
# Dictionary name.values() Return to all dictionaries value,And put it in a similar list dict_values In class
# Dictionary name.items() Return all key and values,All key value pairs form a tuple and are placed in a similar list dict_values In class
a = {"name": "Zhang San", "age": 18, "sex": "male"}

# Note: you can for In the loop, it is obtained by unpacking key and value value
Copy code
 Copy code
# To delete a key value pair, you can use: del Dictionary name["Key name"]
# To delete a dictionary: del Dictionary name
# pop You can also delete a key value pair: dictionary name.pop(Key name,Parameter two),If there is no corresponding key, the second parameter will be returned. If it is not written, an error will be reported directly
# Randomly delete a key value pair: dictionary name.popitem()
# clear Is to empty the dictionary
a = {"name": "Zhang San", "age": 18, "sex": "male"}
del a["name"]
print(a)       # {'age': 18, 'sex': 'male'}
print(a.pop("hobby", "No,"))
a.popitem()    # {'sex': 'male'}
print(a)       # {}
del a
print(a)       # a Deleted, not defined
Copy code

di.setdefault("k111","123")    # Set the value. If the key exists, the original value will be returned. If it does not exist, the first parameter will be inserted into the dictionary as the key and the second parameter as the value, and the value will be returned
di.update({"k1":"111","k2":"324"})        # Set value. If it already exists, it will be overwritten. If it does not exist, it will be filled in. It can also be used in parameters k1=23,k2="daf"This format
Create dictionary from sequence,di.fromkeys({"k1","k2","k3"],123)      # Parameter, the first list is all key,The second is to specify a unified


Tuples cannot be added, deleted or modified

tuple (Tuple) yes Python One of the basic data structures in, similar to a list, but elements in tuples are not allowed to be modified, so tuples are also called read-only lists. Tuples use parentheses - () Wrap, use commas between elements - , The elements in tuples can be strings, numbers, lists, tuples and other data types.

a = (1, 2, 3, [4, 5])
a[3][1] = 9
print(a)        # (1, 2, 3, [4, 9])


Two functions of the collection:

  • Collection can realize the function of de duplication
  • Set can realize relationship test: intersection; Difference set; Union; Subset or not; Is there no intersection

1. Definition of set

There are no duplicate elements in the collection


Define an empty set: the definition of the first method is wrong, and a dictionary is generated; The second method is to correctly define an empty set.


2. Properties of sets

The collection is unordered and does not duplicate data types, so it does not support indexing; section; Repeat and join, only member operators and for Cycle.


3. Add / delete query of set


1. add()—Add a single element


2. update()—Add multiple elements



1. pop()—The first element of the collection is deleted by default, which is just opposite to the list. In particular, it should not be confused with each other.


2. remove()—Deletes the specified element


3. clear()—Empty collection elements

Variable data types: list, dictionary, set
Immutable data types: numeric type, string, tuple
The variable data type realizes a function and directly changes the variable data type;
When an immutable data type implements a function, the result needs to be assigned to another variable;
Is it implemented for loop
Iteratable data types: str,list,tuple,dict,set
Non iteratable data type: numeric type
Do you support index, slice, repeat and join features
Ordered data types: str,list,tuple support
Unordered data types: dict,set I won't support it

Tags: Python

Posted on Mon, 29 Nov 2021 01:06:09 -0500 by kante