[Python study notes] 07 python built-in data types and basic operations

This series of notes for learning Python for yourself, if there are errors, please correct me

Introduction to the most basic built-in data types

Every object has a type, the most basic built-in data type in Python:

  1. Integer

    Integer 234

  2. Floating point

    Decimal 3.14

  3. Boolean

    Indicates true and false only contains True False

  4. String type

    Sequence of strings

digital

Python supports integer and floating point numbers, we can do the following operations on numbers

Operator Description Example structure
+ addition 3+2 5
- Subtraction 30-5 25
* multiplication 3*6 18
/ Floating point division 8/2 4.0
// Integer division 7//2 3
% Modulus (take the remainder) 7%4 3
** power 2**3 8

  • Divide by 0 will generate an exception ZeroDivisionError

  • Use the divmod() function to get the quotient and remainder at the same time


Integer

In python, in addition to decimal, there are other three bases

  • 0b or 0B binary 0 1
  • 0o or 0O eight proceed 0 1 2 3 4 5 6 7
  • 0x or 0X hexadecimal 0 1 2 3 4 5 6 7 8 9 abcdef

These three processes can be very convenient for "bit operation" operations

Use int() to achieve type conversion

  1. Floating point numbers directly round off the decimal part
  2. Boolean value True turns to 1, False turns to 0
  3. If the string conforms to the integer format (floating point format is not acceptable), it will be directly converted to the corresponding integer, otherwise an error will be reported

Automatic transformation

When the integer and floating point numbers are mixed, the expression structure is automatically converted to floating point numbers

How big an integer can be

In python2, int is 32 bits and can store integers from -2147483648 to 2147483647. Long type is 64 bits and can store values ​​between -2 62 and 2 63-1.

In python3, int can store integers of any size, long is cancelled, we can even store the following value: google=10**100

Googol is the original name of Google, which is also the original meaning of Google

The calculation of very large numbers can be used in python3 without causing "integer overflow", which is also a feature of pythonn particularly suitable for scientific computing

Floating point

Floating point number, called float

Floating point numbers use a ∗ bea*b^eabScientific notation in the form of e , for example, 3.14 is represented as314 E − 2 314E-23 1 4 E2 or314 e − 2 314e-23 1 4 e2 These numbers are also stored in the memory with scientific notation.

Type conversion and rounding

  1. Similar to int() we can also use float() to convert it to a floating point number
  2. When the integer and floating-point number are mixed, the expression result is automatically converted into a floating-point number
  3. round(value) can return the rounded value (will not change the original value, but generate a new value)

Enhanced assignment operator

Operator +-* / // ** and% assignment operator can be combined to form an enhanced assignment operator a=a+1 is equivalent to a+=1

Representation of time

The time in the computer is expressed in milliseconds starting from 00:00:00 on January 1, 1970. We also call this moment in 1970 as the unix time point

In python, the current time can be obtained through time.time(), and the returned value is in seconds

Boolean value

There is no Boolean value in Python2, just use the number-to represent False, and the number 1 to represent True

In Python3, True and False are defined as keywords, but their essence is still 1 and 0, and can even be added to numbers

Comparison operator

All comparison operators return 1 for true and return 0 for false, which are equivalent to the special variables True and False respectively

== != > < >= <=

Logical Operators

or and not

Same operator

Compare the storage unit of two objects, the actual comparison is the address of the object

Operator description
is is to determine whether two identifiers refer to the same object
is not is not is to judge whether two identifiers refer to different objects

The difference between is and ==:

is is used to determine whether the two variable reference objects are the same, that is, to compare the address of the object

== is used to determine whether the value of the reference variable reference object is equal, and the __eq__()method of the object is called by default

Constant cache problem

Python only caches smaller integer objects ([-5,256]). Note that this is only executed on the command line, and it is different when pycharm or save files are executed. This is because the interpreter is partially optimized ([-5, any positive integer])

to sum up:

  1. Is compares whether the id values ​​of two objects are equal and whether they point to the same memory address
  2. == compares whether the contents of the two objects are equal and whether the values ​​are equal
  3. Small integer objects [-5,256] are placed in the cache for reuse in the scope of the global interpreter
  4. The is operator is more efficient than ==. When a variable is compared with None, is should be used

String

Basic characteristics of strings

When a lot of people learn programming, they always worry that they are not good at math, and subconsciously think that math is good to program. In fact, most programmers deal with "strings" instead of "numbers". Because programming is to solve Realistic problems, so the importance of logical thinking often exceeds mathematical ability.

The essence of the string is:Character sequence. Python strings are immutable, and we cannot make any changes to the original strings. However, you can copy part of the string to the newly created string to achieve the effect of "looks modified".

Python does not support single character types, and single characters are also used as a string.

String encoding

Python3 directly supports Unicode and can represent characters in any written language in the world. Python3 characters are 16-bit Unicode encoding by default, and ASCII code is a subset of Unicode encoding.

  • Use the built-in function ord() to convert characters into corresponding Unicide codes;
  • Use the built-in function chr() to convert decimal numbers into corresponding characters
print(ord('A'))#65
print(ord('桑'))#26705
print(chr(66))#B
print(chr(20001))#両

Quotation marks create string

We can create a string through single or double quotes, eg: a='abc' b="slp"

The advantage of using two kinds of quotation marks is that we can create strings that contain quotation marks without using escape characters

Three consecutive single quotes or three double quotes can help us create multi-line strings.

Empty string and len() function

Python allows the existence of empty strings, does not contain any characters, and has a length of 0.

len() is used to calculate how many characters the string contains.

Escape character

We can use to "\+特殊字符"achieve some effects that are difficult to express in characters, such as: line feed. Common escape characters are:

Escape character description
\(在行尾时) Line continuation
\\ Backslash
\' apostrophe
\" Double quotes
\b backspace
\n Wrap
\t Horizontal tab
\r Carriage return

String splicing

  1. You can use + to concatenate multiple strings
    • If both sides of + are strings, concatenate
    • If both sides of + are numbers, do addition
    • If the two sides of + are of different types, throw an exception
  2. You can put multiple literal strings directly together to achieve splicing

String copy

Use * to achieve string copy

a = 'Slp'*3
a #SlpSlpSlp

Print without line break

When we called print earlier, a newline character was automatically printed. Sometimes, we don't want to wrap or add newlines automatically. We can add any content to the end by specifying end="any string" by ourselves.

Read the string from the control

We can use input() to read keyboard input from the console.

str() implements digital transformation string

str() can help us convert other data types to strings

When we call the print() function, the interpreter automatically calls str() to convert the string object into a string.

Use [] to extract characters

The essence of a string is a sequence of characters. We can add [] after the string, and specify it in [], which can extract a single character at that position.

  • Forward search: the first character on the left, the offset is 0, the second offset is 1, and so on, until len(str)-1
  • Reverse search: the first character on the far right, the offset is -1, the second offset of the derivative is -2, and so on, until -len(str)

replace() implements string replacement

The string is immutable, we can get the character at the specified position of the string through [], but we cannot change the string, if we try to change a character, there will be an errorTypeError :'str' object does not support item assignment

The string cannot be changed, but we do need to replace it sometimes. At this time, we can only achieve it by creating a new string.

a = '123'
a = a.replace('1','4')

In the whole process, a new string object is actually created and pointed to a instead of modifying the previous string.

String slice operation

The slice operation allows us to quickly extract substrings, the standard format is: [start offset start: end offset end: step size]

The typical operation (when the three quantities are positive) is as follows:

Operation and instructions Example result
[:] Extract the entire string abcdef[:] abcdef
[stsrt:] From the start index to the end abcdef[2:] cdef
[:end]From the beginning to end-1 abcdef[:2] from
[start:end] From start to end-1 abcdef[2:4] cd
[start:end:step]From start to end-1, the step length is step abcdef[1:5:2] bd

Other operations (three numbers are negative):

Example Description result
“abcdefghijk”[-3:] Countdown 3 ijk
“abcdefghijkstuvwxyz”[-8:-3] The 8th from the bottom to the 3rd from the bottom (the header does not include the tail) stuvw
“abcdefghijkstuvwxyz”[::-1] The step size is negative, and the extraction is reversed from right to left zyxwvutsrqponmlkjihgfedcba

During the slicing operation, the start offset and end offset are not in the range of [0, string length-1], and no error will be reported. Start offset less than 0 will be treated as 0, end offset greater than length -1, it will be treated as -1

split() separation and join() merge

split() can split a string into multiple substrings (stored in a list) based on the specified separator. If no delimiter is specified, blank characters (newline/space/tab) are used by default

The role of join() is the opposite of that of split(), which is used to join a series of substrings.

print(a.split())
b=['s','l','p']
print("".join(b))

Key points of splicing strings:

Using the string splicing character + will produce new string objects, so it is not recommended to use + to splice strings. It is recommended to use the join function, because the join function calculates the length of all strings before concatenating the strings, and then copies them one by one, creating a new object only once.

String resident mechanism and string identity judgment

String residency: only save a copy of the same immutable string. Different values ​​are stored in the string residency pool. Python supports the string residency mechanism. For strings that conform to the identifier rules (underscore Number) will enable string persistence

Summary of common string methods

Common search methods
Methods and usage examples Description result
len (a) String length
a.startwith(‘ss’) Start with the specified string
a.endswith(‘tt’) End with the specified string
a.find(‘s’) The first occurrence of the specified string
a.rfind(‘t’) The position of the last occurrence of the specified string
a.count(’a‘) How many times the specified string appears
a.isalnum() 所有字符全是字母或数字
去除首尾信息

我们可以使用strip()去除字符串收尾指定信息,通过lstrip()去除字符串左边指定信息,rstrip()去除字符串右边指定信息

大小写转换
示例 说明 结果
a.capitalize() 产生新的字符串,首字母大写
a.title() 产生新的字符串,每个单词都首字母大写
a.upper() 产生新的字符串,所有字符全部转成大写
a.lower() 产生新的字符串,所有字符全转成小写
a.swapcase() 产生新的,所有字母大小写转换
格式排版

center() ljust() rjust()这3个函数用于对字符串实现排版

字符串格式化
  • format()基本用法:基本语法是通过{}和:来代替以前的%,format函数可以接受不限个数参数,位置可以不按顺序。

    a="名字是:{0},年龄是:{1}"
    print(a.format('slp','18'))
    b="名字是:{0},年龄是{1},{0}是个努力的小姑娘"
    print(b.format('slp',18))
    c="名字是{name},年龄是{age}"
    print(c.format(age=18,name='slp'))
    

    我们可以通过{索引}/{参数名},直接映射参数值,实现对字符串的格式化。

  • 填充与对齐

    填充常跟对齐一起使用

    ^ < > 分别是居中,左对齐 右对齐后面带宽度

    :后面带填充的字符,只能是一个字符不指定则默认用空格填充。

  • 数字格式化

    浮点数通过f,整数通过d进行需要的格式化

    格式 描述 输出
    {:.2f} 保留小数点后两位
    {:+.2f} 带符号保留小数点后两位
    {:.0f} 不带小数
    {:0>2d} 数字补0,填充左侧,宽度为2
    {:x<4d} 数字补x,填充右边,宽度为4
    {:,} 以逗号分隔的数字格式
    {:.2%} 百分比格式
    {:.2e} 指数记法
    {:10d} 右对齐,(默认,宽度为10)
    {:<10d} 左对齐,(宽度为10)
    {:^10d} 中间对齐(宽度为10)
可变字符串

在python中,字符串属于不可变对象,不支持原地修改,如果需要修改其中的值,只能创建新的字符串对象,但是,经常我们确实需要原地修改字符串,可以使用ioStringIO对象或array模块

import io
s = 'hello slp'
sio = io.StringIO(s)
print(sio)
print(sio.getvalue())
print(sio.seek(7))
print(sio.write('g'))
print(sio.getvalue())
其他方法
  1. isalnum():是否为字母或数字
  2. isalphal():检测字符串是否只由字母组成(含汉字)
  3. isdigit():检测字符串是否只由数字组成
  4. isspace():检测是否为空白符
  5. isupper():是否为大写字母
  6. islower():是否为小写字母

基本运算符

运算符 说明
or and not 布尔或 布尔与 布尔非
is 、 is not 同一性判断,判断是否为同一个对象
< <= > >= != == 比较值是否相当,可以连用
| ^ & 按位或 按位异或 按位与
<< >> 移位
~ 按位翻转
+ - * / // % 加 减 乘 除 整数除 取余
** 幂运算
运算符优先级

由高到低

运算符 描述
** 指数
~ + - 按位翻转 一元加号和减号
* / // % 乘 除 取模 取整除
+ - 加法 减法
>> << 右移 左移运算符
& 位 AND
^ | 位运算符
<= < > >= 比较运算符
<> == != 等于运算符
= %= /= //= -= *= **= 赋值运算符
is 、is not 身份运算符
in 、not in 成员运算符
not and or 逻辑运算符

微信搜一搜【梓莘】或扫描下方二维码交个朋友共同进步。文章持续更新中。目前在整理python百战学习笔记,期待后续更多的更新哦。
在这里插入图片描述

Guess you like

Origin blog.csdn.net/weixin_51656605/article/details/112322526