Python Basics - Data Types

Python Number

From the literal meaning, we can know that it is a data type used to store numbers.
Second note that:

  1. The data type cannot be changed. If we change the Number data type, the system will reallocate the memory space
  2. The Number object will be created when the instance is assigned.
    For example :
    a = 1,b = 2
    where a, b are references to the Number object
    Python provides four (Long is not available in Python3, it is now in Python2)
    1) Integer
    Integer is a number without a decimal point, there are positive and negative
    2) Long Integer Integer of
    infinite size, the difference between integers is that there is an L or l at the back
    3) Floating point type The type of numbers
    with a fractional part
    4) Complex numbers
    There are real numbers It can be represented by a + bj, or complex(a,b), the real part a and the imaginary part b of the complex number are both floating-point types.
There are numbers that involve operations, so Python provides the math and cmath modules

illustrate:

  1. Math provides common mathematical operation functions
  2. Operations on complex numbers are included in cmath
  3. The functions contained in the two modules are basically the same, only the complex number operation and the real number operation are different.
    As for the functions provided in math, they are not listed here, only the viewing method is provided here.

First, we need to import the package, import math so that we introduce math,
then we use dir(math) to view all functions
Finally , we can use help(math. function name) to view the specific function usage

Several functions are highlighted here:
  1. range() function
    This function represents a continuous segment of integers.
    For example, range(1,5) represents [1,2,3,4] excluding 5
    range(1,5,2) represents [1,3] The third parameter represents the step size
  2. cmp()
    This function is not available in python3,
    but can be replaced with
    operator.lt(a, b) lt(a, b) is equivalent to a < b
    operator.le(a, b) le(a,b) is equivalent For a <= b
    operator.eq(a, b) eq(a,b) is equivalent to a == b
    operator.ne(a, b) ne(a,b) is equivalent to a != b
    operator.ge(a , b) gt(a,b) is equivalent to a > b
    operator.gt(a, b) ge(a, b) is equivalent to a>= b
  3. abs() and fabs()
    are functions that take absolute values
the difference:
    a) abs直接内置的可以直接用,fabs必须引入math模块
    b) abs返回的是整数,fabs反会的是小数
Python string

I have already written about the creation of strings in the first article on Python, and I will not repeat them here.
Note : There is no char type in our java in python, nor the concept of a single character, whether it is single quotes or double quotes and triple quotes are all represented. String
such as str = 'hello word!' How to get a certain value in it? ?
1. At this time, str[0] represents h, that is, the first character str[1] is e, that is, the second character can be obtained by analogy
. 2. Slicing can be used, and str[1:5] represents The is ello Note that this means the second character to the sixth, excluding the sixth

string operator

a = ‘hello’ b = ‘rocky’

1.+ 表示 字符串的拼接  a+b 表示‘hello’+’rocky’
2.* 表示重复字符串 a*2 表示 ‘hellohello’
3.[] 通过索引取出字符串中的字符 a[0] 表示h
4.[:] 截取字符串 a[0:3]表示hel
5.In 成员运算符如  ‘h’ in a 表示True 说明 a中含有’h’字符 否则返回False
6.not in 和in用法类似 只是表示不含有的意思
7.r/R 原始字符 例如 print r’\n’ 则表示原样输出
8.% 格式字符串 例如 print "My name is %s and weight is %d kg!" % ('Rocky', 21) 则表示把’Rocky 放入第一个%s 处 21 放入%d处’ 
python string formatting symbols

write picture description here

String built-in functions

Only some common ones are listed here, he can use help Wendan to view

1.string.capitalize() 把字符串的第一个字符大写
2.string.center(width) 返回一个原字符串居中,并使用空格填充至长度 width 的新字符串
3.string.count(str, beg=0, end=len(string)) 返回 str 在 string 里面出现的次数,如果 beg 或者 end 指定则返回指定范围内 str 出现的次数
4.string.endswith(obj, beg=0, end=len(string)) 检查字符串是否以 obj 结束,如果beg 或者 end 指定则检查指定的范围内是否以 obj 结束,如果是,返回 True,否则返回 False.
5.string.find(str, beg=0, end=len(string)) 检测 str 是否包含在 string 中,如果 beg 和 end 指定范围,则检查是否包含在指定范围内,如果是返回开始的索引值,否则返回-1
6.string.format() 格式化字符串
7.string.index(str, beg=0, end=len(string))跟find()方法一样,只不过如果str不在 string中会报一个异常.
8.string.isalpha() 如果 string 至少有一个字符并且所有字符都是字母则返回 True,
否则返回 False
9.string.isdecimal() 如果 string 只包含十进制数字则返回 True 否则返回 False.
10.string.isdigit() 如果 string 只包含数字则返回 True 否则返回 False.
11.string.islower() 如果 string 中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是小写,则返回 True,否则返回 False
12.string.isnumeric() 如果 string 中只包含数字字符,则返回 True,否则返回 False
13.string.isspace() 如果 string 中只包含空格,则返回 True,否则返回 False.
14.string.istitle() 如果 string 是标题化的则返回 True,否则返回 False
15.string.isupper() 如果 string 中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是大写,则返回 True,否则返回 False
16.string.join(seq) 以 string 作为分隔符,将 seq 中所有的元素(的字符串表示)合并为一个新的字符串
17.string.ljust(width) 返回一个原字符串左对齐,并使用空格填充至长度 width 的新字符串
18.string.lower() 转换 string 中所有大写字符为小写.
19.string.lstrip() 截掉 string 左边的空格
20.max(str) 返回字符串 str 中最大的字母。
21.min(str) 返回字符串 str 中最小的字母。
22.string.replace(str1, str2,  num=string.count(str1)) 把 string 中的 str1 替换成 str2,如果 num 指定,则替换不超过 num 次.
23.string.rfind(str, beg=0,end=len(string) ) 类似于 find()函数,不过是从右边开始查找.
24.string.rindex( str, beg=0,end=len(string))类似于 index(),不过是从右边开始.
25.string.rjust(width) 返回一个原字符串右对齐,并使用空格填充至长度 width 的新字符串
26.string.rstrip() 删除 string 字符串末尾的空格.
27.string.split(str="", num=string.count(str)) 以 str 为分隔符切片 string,如果 num有指定值,则仅分隔 num 个子字符串
28.string.splitlines([keepends]) 按照行('\r', '\r\n', \n')分隔,返回一个包含各行作为元素的列表,如果参数 keepends 为 False,不包含换行符,如果为 True,则保留换行符。
29.string.startswith(obj, beg=0,end=len(string)) 检查字符串是否是以 obj 开头,是则返回 True,否则返回 False。如果beg 和 end 指定值,则在指定范围内检查.
30.string.strip([obj]) 在 string 上执行 lstrip()和 rstrip()
31.string.swapcase() 翻转 string 中的大小写
32.string.title() 返回"标题化"string,就是说所有单词都是以大写开始,其余字母均为小写
33.string.upper() 转换 string 中的小写字母为大写
34.string.isdecimal()  isdecimal()方法检查字符串是否只包含十进制字符。这种方法只存在于unicode对象。
Python List (List)

Sequences are the most basic data structure in Python. Each element in the sequence is assigned a number -- position or index, where the first index is 0, the second index is 1, and so on.
Operations that can be performed on sequences include indexing, slicing, adding, multiplying, and checking members.
Additionally, Python has built-in methods for determining the length of a sequence and determining the largest and smallest elements.
Lists are the most commonly used Python data type, which can appear as comma-separated values ​​within square brackets.
The data items of the list do not need to have the same type

list creation

list1 = [11,'rocky',21],list2 = [1, 2, 3, 4, 5, 6, 7 ]
So we have created 2 lists, which can be characterized by:

  1. Lists are enclosed in square brackets
  2. The data type of the list is not required to be consistent,
  3. Each element of the list is separated by a comma
List usage
取值
    取出列表中的值是通过索引完成的,注意不要索引越界!!!
    例如:list1[1] 表示的是列表list1的第二个元素’Rocky’
    当然Python也提供了切片取值
    如:lsit2[1:5] 表示的是[2, 3, 4, 5]
改值
    我们可以修改原有的值,也可以新填入值到列表
    list1[0] = ‘I’ 这样 lsit1 就变成了[‘I,’rocky’,21]
    新填入:list1.append(‘Love’)
    这时候 list1 为[‘I,’rocky’,21,’Love’] 课件append只是吧值插入到最后一个,那么是否还有吧值插入到指定位置的方法?
    list1.insert(1,'Love') 这时候 list1变成了['I', 'Love', 'rocky', 21]
删值
    删除list中的值我们提供了两种方式:
    1.del 
    使用del删除元素 del list1[2] 这样就把list1中第三个元素删除了
    del lsit1 是把整个list1删除
    2.remove()
    这种方式只能按索引删除,可以删除指定索引位置的元素
List common functions
1   cmp(list1, list2) 比较两个列表的元素
2   len(list) 列表元素个数
3   max(list) 返回列表元素最大值
4   min(list) 返回列表元素最小值
5   list(seq) 将元组转换为列表
6   list..append(obj) 在列表末尾添加新的对象
7   list..count(obj) 统计某个元素在列表中出现的次数
8   list..extend(seq) 在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)
9   list..index(obj) 从列表中找出某个值第一个匹配项的索引位置
10  list..insert(index, obj) 将对象插入列表
11  list..pop(obj=list[-1]) 移除列表中的一个元素(默认最后一个元素),并且返回该元素的值
12  list..remove(obj) 移除列表中某个值的第一个匹配项
13  list..reverse() 反向列表中元素
14  list..sort([func]) 对原列表进行排序
Python tuple

Python tuples are similar to lists, except that the elements of the tuple cannot be modified.
Use parentheses for tuples and square brackets for lists.
Tuple creation is as simple as adding elements in parentheses and separating them with commas.
Create a tuple:
t = ('I','Love','Rocky')
Note: When the tuple has only one element, such as ('I',), there must be a comma after it, and it cannot be omitted! ! ! !

Use of tuples
取值
    元组的取值和列表类似 不在赘述
修改
    元组不可修改元组内的值,只是可以拼接元组
    如:tup1 = (12, 34.56);
    tup2 = ('abc', 'xyz');
    可以打得到新的元组
    tup3 = tup1 + tup2;
删除
    元组的删除和list的del删除一致
no closing separator

Any unsigned object, separated by commas, defaults to a tuple, as in the following example:

print 'abc', -4.24e93, 18+6.6j, 'xyz';
x, y = 1, 2;
print "Value of x , y : ", x,y;
运行结果:
    abc -4.24e+93 (18+6.6j) xyz
    Value of x , y : 1 2
Tuple built-in functions
  1. cmp(tuple1, tuple2) compares two tuple elements.
  2. len(tuple) counts the number of elements in a tuple.
  3. max(tuple) returns the maximum value of the element in the tuple.
  4. min(tuple) returns the minimum value of the elements in the tuple.
  5. tuple(seq) converts a list to a tuple.
Supplement on Indexing in Sequences
  1. The index does not have to be an integer greater than or equal to 0 can be negative
  2. Slicing (complement to truncation)
    now takes tuples as an example:
t = (‘I’,’Love’,’Rocky’)

其中t[1] 表示Love 这是大家知道的

那么t[-1]?   其实它表示的而是最后一个元素 t[-2]表示倒数第二个元素,以此类推

t[1:2] 表示Love 这也是大家知道的 ('Love',)

那么t[1:]??  其实它是表示从第二个开始到最后的元素 ('I', 'Love')

那么t[:-1]??? 其实它是表示 ('I', 'Love') 即表示 除了最后一个元素外的所有元素的组成的元组 t[:-2] 为 ('I',) 这种形式意思就是 从开始到倒数第几个元素组成的元组
Python dictionary (Dictionary)

Dictionaries are another mutable container model and can store objects of any type.
Features:

  1. Each key value key of the dictionary corresponds to a value, and the key value is separated by a colon:
  2. Separate each key-value pair with a comma,
  3. The entire dictionary is enclosed in curly braces {}

The format is as follows:
d = {key1 : value1, key2 : value2 }

Notice:

  1. The key is unique to meet our needs, otherwise, the key value stored later will overwrite the original key value of the same key! ! !
  2. Keys must be immutable, so they can be numbers, strings, or tuples, but not lists
use of dictionaries

dict = {‘Name’: Rocky, ‘Age’:21, Weight: 183};

取值
    字典的取值是根据key来取值的,
    如:
    print "dict['Name']: ", dict['Name']; 结果为Rocky
    print "dict['Age']: ", dict['Age']; 结果为 21
    注意 在取值的时候如果没有key,即所输入的key不存在字典里面,
    会报错:KeyError: ‘输入的key’
修改
    dict['Age'] = 8; #这是修改Age 的值
    dict['School'] = "DPS School"; # 这回事新添加'School'键值
删除
    del dict['Name']    # 删除键是'Name'的条目
    dict.clear()        # 清空词典所有条目
    del dict            # 删除词典
Dictionary built-in functions & methods
Python字典包含了以下内置函数:

1   cmp(dict1, dict2) 比较两个字典元素。
2   len(dict) 计算字典元素个数,即键的总数。
3   str(dict) 输出字典可打印的字符串表示。
4   type(variable) 返回输入的变量类型,如果变量是字典就返回字典类型。

Python字典包含了以下内置方法:

1   dict.clear() 删除字典内所有元素
2   dict.copy() 返回一个字典的浅复制
3   dict.fromkeys(seq[, val]) 创建一个新字典,以序列 seq 中元素做字典的键,val 为字典所有键对应的初始值
4   dict.get(key, default=None) 返回指定键的值,如果值不在字典中返回default5   dict.has_key(key) 如果键在字典dict里返回true,否则返回false
6   dict.items() 以列表返回可遍历的(键, 值) 元组数组
7   dict.keys() 以列表返回一个字典所有的键
8   dict.setdefault(key, default=None) 和get()类似, 但如果键不存在于字典中,将会添加键并将值设为default
9   dict.update(dict2) 把字典dict2的键/值对更新到dict里
10  dict.values() 以列表返回字典中的所有值
11  pop(key[,default]) 删除字典给定键 key 所对应的值,返回值为被删除的值。key值必须给出。 否则,返回default值。
12  popitem() 随机返回并删除字典中的一对键和值。

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324834006&siteId=291194637