Basic data types

Variable types

Counter = 100 # int miles = 1000.0 # float variable name = “runoob” # string

Variable assignment

a = b = c = 1

a, b, c = 1, 2, “runoob”

Of the six standard data types for Python3:

Immutable data (3) : Number (Number), String (String), Tuple (Tuple) Mutable data: List, Dictionary, Set A complex Number consists of a real and an imaginary part and can be represented by a + bj or complex(a,b). Both the real part a and the imaginary part B of the complex Number are floating point types.

> > > a, b, c, d = 12,13.0, True,'sss'
>>> print(type(a),type(b),type(c),type(d))
<class 'int'> <class 'float'> <class 'bool'> <class 'str'> >>> 2/4Divide to get a floating point number
0.5
>>> 2 // 4 Divide, get an integer
0
Copy the code

2. String Strings in Python are enclosed in single or double quotation marks, and special characters are escaped using backslashes. Python has no separate character types; a character is a string of length 1. The syntax for truncating a string is as follows: The index value of a variable [header subscript: tail subscript] starts at 0 and -1 starts at the end.


#! /usr/bin/python3
str = 'Runoob'
print (str)          # output string
print (str[0:-1])    Print all characters from the first to the penultimate
print (str[0])       # Print the first character of the string
print (str[2:5])     # print characters from the third to the fifth
print (str[2:])      # print all characters from the third
print (str * 2)      Print the string twice
print (str + "TEST") # connect string
Copy the code

Python uses backslashes () to escape special characters. If you don’t want backslashes to escape, you can add an r before the string to indicate the original string:

>>> print('Ru\noob')
Ru
oob
>>> print(r'Ru\noob')
Ru\noob
>>> 
Copy the code

In addition, a backslash () can be used as a line continuation, indicating that the next line is a continuation of the previous line. You can also use “””…” “” or” ‘… “” spans multiple lines. 3. The List variable [header subscript: tail subscript], the index value starts at 0, -1 is the starting position from the end.

#! /usr/bin/python3
 
list = [ 'abcd', 786, 2.23,'runoob', 70.2] tinyList = [123,'runoob']
 
print (list)            Print the complete list
print (list[0])         Print the first element of the list
print (list[1:3])       # Output from the second to the third element
print (list[2:])        Output all elements starting with the third element
print (tinylist * 2)    Print the list twice
print (list + tinylist) # list of connections
Copy the code

The following output is displayed:

['abcd', 786, 2.23, 'runoob', 70.2]
abcd
[786, 2.23]
[2.23, 'runoob'70.2], [123,'runoob', 123, 'runoob']
['abcd', 786, 2.23, 'runoob', 70.2, 123, 'runoob']
Copy the code

Unlike Python strings, elements in a list can be changed:

>>>a = [1, 2, 3, 4, 5, 6]
>>> a[0] = 9
>>> a[2:5] = [13, 14, 15]
>>> a
[9, 2, 13, 14, 15, 6]
>>> a[2:5] = []   # set the corresponding element value to []
>>> a
[9, 2, 6]
Copy the code

Python list interception can take a third argument that intercepts the step size. The following example intercepts a string at indexes 1 through 4 and sets the step size to 2 (one place apart) :

def reverseWords(input): 
      
    # String delimiters with Spaces to separate words into lists
    inputWords = input.split("") 
  
    # flip string
    List = [1,2,3,4]
    # list[0]=1, list[1]=2, and -1 =1
    # inputWords[-1::-1] takes three parameters
    The first argument -1 represents the last element
    The second argument is empty, indicating that the list is moved to the end
    The third parameter is the step size, -1 indicates the reverse
    inputWords=inputWords[-1::-1] 
  
    # recombine strings
    output = ' '.join(inputWords) 
      
    return output 
  
if __name__ == "__main__": 
    input = 'I like runoob'
    rw = reverseWords(input) 
    print(rw)
Copy the code

The output is:

runoob like I
Copy the code

A Tuple is similar to a list except that the elements of a Tuple cannot be modified. Tuples are written in parentheses (), with elements separated by commas. Element types in tuples can also be different.

#! /usr/bin/python3
 
tuple = ( 'abcd', 786, 2.23,'runoob', 70.2) tinytuple = (123,'runoob')
 
print (tuple)             Output the full tuple
print (tuple[0])          Print the first element of the tuple
print (tuple[1:3])        The output starts from the second element to the third element
print (tuple[2:])         Output all elements starting with the third element
print (tinytuple * 2)     Print the tuple twice
print (tuple + tinytuple) # connect tuples
Copy the code

The output of the above example is as follows:

('abcd', 786, 2.23, 'runoob', 70.2)
abcd
(786, 2.23)
(2.23, 'runoob'70.2), (123,'runoob', 123, 'runoob')
('abcd', 786, 2.23, 'runoob', 70.2, 123, 'runoob')
Copy the code

Tuples are similar to strings in that they can be indexed and the subscript index starts at 0, with -1 being the position starting from the end. You can intercept it. Instead, you can think of a string as a special kind of tuple.

>>>tup = (1, 2, 3, 4, 5, 6)
>>> print(tup[0])
1
>>> print(tup[1:5])
(2, 3, 4, 5)
>>> tup[0] = 11  It is illegal to modify a tuple element
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>>
Copy the code

Although the element of a tuple is immutable, it can contain mutable objects, such as a list list. Constructing tuples with 0 or 1 elements is special, so there are some additional syntax rules:

tup1 = ()    # empty tuple
tup2 = (20,) An element that requires a comma after the element
Copy the code

Strings, lists, and tuples are all sequences. Note:

  • As with strings, elements of tuples cannot be modified.
  • Tuples can also be indexed and sliced in the same way.
  • Note the special syntax rules for constructing tuples containing 0 or 1 elements.
  • Tuples can also be concatenated using the + operator.

例 句 : A Set object is an unordered Set of hashable values whose members can act as keys in a dictionary. Collections support checking members with the IN and not in operators, getting the cardinality (size) of the collection from len() built-in functions, and iterating over members of the collection with a for loop. But because the collection itself is unordered, it cannot be indexed or sliced, and there are no keys to retrieve the values of the elements in the collection. The basic functionality is membership testing and removing duplicate elements. You can use curly braces {} or the set() function to create a collection. Note: To create an empty collection, you must use set() instead of {}, because {} is used to create an empty dictionary. A set is the same as a dict, but without a value. It is equivalent to a set of dict keys. Since dict keys are non-repetitive and immutable, sets also have the following features:

  • Don’t repeat
  • Elements are immutable objects

Create format:

parame = {value01,value02,... } orset(value)
Copy the code

Examples are as follows:

#! /usr/bin/python3
 
student = {'Tom'.'Jim'.'Mary'.'Tom'.'Jack'.'Rose'}
 
print(student)   # output set, duplicate elements are automatically removed
 
# Member test
if 'Rose' in student :
    print('Rose is in the set ')
else :
    print('Rose is not in the set ')
 
 
# set can perform set operations
a = set('abracadabra')
b = set('alacazam')
 
print(a)
 
print(a - b)     The difference between a and b
 
print(a | b)     # union of a and b
 
print(a & b)     # Intersection of A and B
 
print(a ^ b)     The elements of a and B that do not coexist
Copy the code

The output of the above example is as follows:

{'Mary'.'Jim'.'Rose'.'Jack'.'Tom'} Rose in the collection {'b'.'a'.'c'.'r'.'d'}
{'b'.'d'.'r'}
{'l'.'r'.'a'.'c'.'z'.'m'.'b'.'d'}
{'a'.'c'}
{'l'.'r'.'z'.'m'.'b'.'d'}
Copy the code

Dictionaries are another very useful built-in data type in Python. Lists are ordered collections of objects, dictionaries are unordered collections of objects. The difference is that elements in dictionaries are accessed by keys, not by offsets. A dictionary is a mapping type. A dictionary is identified by {}. It is an unordered set of keys: values. Keys must be of immutable type. A key must be unique in the same dictionary.

#! /usr/bin/python3
 
dict = {}
dict['one'] = "1 - Rookie Tutorial"
dict[2]     = "2 - Rookie tools"
tinydict = {'name': 'runoob'.'code': 1,'site': 'www.runoob.com'}
print (dict['one'])       # output the value with the key 'one'
print (dict[2])           Print the value of key 2
print (tinydict)          Print the complete dictionary
print (tinydict.keys())   Print all keys
print (tinydict.values()) # output all values
Copy the code

The output of the above example is as follows:

1 - Rookie tutorial 2 - Rookie tools {'name': 'runoob'.'code': 1, 'site': 'www.runoob.com'}
dict_keys(['name'.'code'.'site'])
dict_values(['runoob', 1, 'www.runoob.com'])
Copy the code

The dict() constructor builds a dictionary directly from a sequence of key-value pairs as follows:

>>>dict([('Runoob', 1), ('Google', 2), ('Taobao'And 3)]) {'Taobao': 3.'Runoob': 1, 'Google': 2}
 
>>> {x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}
 
>>> dict(Runoob=1, Google=2, Taobao=3)
{'Runoob': 1, 'Google': 2.'Taobao': 3}
Copy the code

In addition, dictionary types have built-in functions such as clear(), keys(), values(), and so on. Note:

  • A dictionary is a type of mapping whose elements are key-value pairs.
  • Dictionary keywords must be immutable and cannot be repeated.
  • To create an empty dictionary use {}.

Python data type conversion

Sometimes, we need to convert data to built-in types. To convert data types, you just need to use the data type as the function name. The following built-in functions perform conversions between data types. These functions return a new object representing the value of the transformation.

function describe
int(x [,base]) Convert x to an integer
float(x) Convert x to a floating point number
complex(real [,imag]) Create a complex number
str(x) Convert object X to a string
repr(x) Convert object X to an expression string
eval(str) Evaluates a valid Python expression in a string and returns an object
tuple(s) Converts the sequence S to a tuple
list(s) Convert the sequence S to a list
set(s) Convert to a mutable set
dict(d) Create a dictionary. D must be a key,value tuple.
frozenset(s) To an immutable set
chr(x) Converts an integer to a 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