- Original blog address: Detailed explanation of Python data types 02
- Some commonly used data types are mainly introduced in the Python data type detailed explanation 01 above .
Python
- This article mainly introduces some
Python
of the commonly used modules in
1. Number
Python
The functions commonly used in mathematical operations in Chinese are basically inmath
modules andcmath
modules.math
The module provides many mathematical operations on floating-point numbers.cmath
The module contains some functions for complex number operations.cmath
The function of themath
module is basically the same as the function of the module, the difference is that thecmath
module operates on complex numbers, and themath
module operates on mathematical operations.- To use the
math
orcmath
function you must first import:
import math
# 或者
import cmath
1. Python math constants
math
Three math constants are defined in the module
# 自然常数 e
e = 2.718281828459045
# 圆周率,一般以π来表示
pi = 3.141592653589793
# 2π
tau = 6.283185307179586
2. Python trigonometry
For direct access, you need to import the math
module , and then call the method through the math static object
function | describe |
---|---|
acos(x) | Returns the arc cosine of x in radians. |
asin(x) | Returns the arcsine of x in radians. |
atan (x) | Returns the arctangent of x in radians. |
atan2(y, x) | Returns the arctangent of the given X and Y coordinate values. |
cos(x) | Returns the cosine of x in radians. |
hypot(x, y) | Returns the Euclidean norm sqrt(x*x + y*y) . |
sin(x) | Returns the sine of x radians. |
tan(x) | Returns the tangent of x radians. |
degrees(x) | Convert radians to degrees, such as degrees(math.pi/2), return 90.0 |
radians(x) | Convert degrees to radians |
3. Python math functions
function | return value (description) |
---|---|
abs(x) | Returns the absolute value of the number, such as abs(-12) returns 12 |
ceil(x) | Returns the rounded integer of the number (the decimal is rounded up), such as math.ceil(4.1) returns 5, math.ceil(4.0) returns 4 |
cmp(x, y) | If x < y returns -1, if x == y returns 0, if x > y returns 1; (Python is deprecated in 3.x) |
exp(x) | Returns e raised to the power of x, such as math.exp(2) returns 7.38905609893065 |
fabs(x) | Returns the absolute value of the number, such as math.fabs(-10) 10.0 |
floor(x) | Returns the rounded integer of the number (the decimal is rounded down), such as math.floor(4.9) returns 4 |
log(x) | If math.log(math.e) return 1.0, math.log(100,10) return 2.0 |
log10(x) | Returns the logarithm of x in base 10, such as math.log10(100) 2.0 |
max(x1, x2,…) | Returns the maximum value for the given argument, which can be a sequence. |
min(x1, x2,…) | Returns the minimum value of the given argument, which can be a sequence. |
modf(x) | Returns the integer part and the fractional part of x (in tuple form), the numerical signs of the two parts are the same as x, and the integer part is represented by a floating point type; for example: math.modf(99.09) , returns (0.09000000000000341, 99.0) |
pow(x, y) | x**y The value after the operation. |
round(x [,n]) | Returns the rounded value of the floating-point number x, if n is given, it represents the number of digits after the decimal point; such as round(90.09, 1) output: 90.1; such as: round(90.09) output: 90 |
sqrt(x) | Return the square root of the number x, such as: math.sqrt(4) return 2.0 |
- where abs()
and the fabs()
difference
- abs()
is a built-in function, and is defined fabs()
in math
a module.
- fabs()
function only works on float
sum integer
types, but abs()
also works on complex numbers
4. Python random number function
- Random numbers can be used in mathematics, games, security and other fields, and are often embedded in algorithms to improve algorithm efficiency and improve program security.
- The random number function needs to import the
random
module , and thenrandom
call the function method through the static object Python
Contains the following common random number functions:
4-1. choice
Randomly pick an element from the elements of a sequence (tuple, list, string)
import random
random.choice( seq )
# 测试用例
# 从序列的元素中随机挑选一个元素
print(random.choice((1, 3, 5, 2)))
print(random.choice([1, 2, 3, 4]))
# 随机返回一个字符
print(random.choice("titanjun"))
4-2. randrange
Returns a random number in the specified increasing radix set, the default radix default value is 1, the default type is int
randrange(self, start, stop=None, step=1, _int=int)
- parameter
start
– The starting value in the specified range, inclusive.stop
– End value in the specified range, not included in the range.step
– Specify the increment base
# 输出 100 <= number < 1000 间的随机偶数
print(random.randrange(100, 1000, 2))
4-3. random
A randomly generated real number in the range [0,1)
print(random.random())
4-4. seed
This function has no return value, change the seed of the random number generator to generate the same random number
random.seed(5)
print(random.random())
random.seed()
print(random.random())
4-5. shuffle
- Randomly sort all elements of a list, no return value
- Since tuples do not support secondary assignment, tuples do not support rearrangement
# 将序列的所有元素随机排序
list1 = [1, 2, 3, 4]
random.shuffle(list1)
print(list1)
4-6. uniform
- Randomly generate a real number in the range [x, y)
- parameter:
- x – The smallest random number, inclusive.
- y – The maximum value of random numbers, not including this value.
print(random.uniform(2, 5))
2. String
The previous article Python Data Types Explained 01 introduces some basic knowledge of strings. Here we mainly introduce the functions and syntax commonly used in character creation.
1. in
andnot in
Check if a string contains the specified string
# 判断字符串中是否包含某字符串
str = 'Hello Python'
if ('llo' in str):
str += ' True'
else:
str += ' False'
print(str)
# 判断字符串是否不包含某字符串
if ('py' not in str):
str += ' not in'
else:
str += ' in'
print(str)
// 分别输出
Hello Python True
Hello Python True not in
2. String formatting
Format other types of data as strings and return them, %
separate strings from other types
symbol | describe |
---|---|
%c |
Formatting characters and their ASCII codes |
%s |
format string |
%d |
format integer |
%u |
format unsigned int |
%o |
format unsigned octal number |
%x |
format unsigned hexadecimal number |
%X |
format unsigned hexadecimal number (uppercase) |
%f |
Format a floating point number, specifying the precision after the decimal point |
%e |
Format floating point numbers in scientific notation |
%E |
Same as %e, format floating point numbers in scientific notation |
%g |
Shorthand for %f and %e |
%G |
Shorthand for %f and %E |
%p |
Format the address of a variable with a hexadecimal number |
How to use
print('che is %d' % 19)
// 跟C语言的写法
prin他("che is %d", 19)
3. str.format()
Function
Python2.6
At the beginning, a function for formatting strings was addedstr.format()
, which enhanced the function of string formatting.
The basic syntax{}
is:
replaced by and%
.format
A function can accept an unlimited number of arguments, and the positions can be out of order.
Simple to use
# format函数
# 不设置指定位置,按默认顺序
str1 = '{} {}'.format('hello', 'python')
print(str1)
# 设置指定位置
str2 = '{0}{1}'.format('Python', '字符串')
print(str2)
# 设置指定位置
str3 = '{1} {0} {1}'.format('hello', 'che')
print(str3)
# 设置参数
print("姓名: {name}, 年龄: {age}".format(name='che', age=18))
# 设置字典参数
dic = {'name': 'jun', 'age': 20}
print("姓名: {name}, 年龄: {age}".format(**dic))
# 设置列表参数
list0 = ['titan', 20]
print("姓名: {0[0]}, 年龄: {0[1]}".format(list0))
/*输出结果
hello python
Python字符串
che hello che
姓名: che, 年龄: 18
姓名: jun, 年龄: 20
姓名: titan, 年龄: 20
*/
4. Formatting operator helper instructions
The specific use of related operators will be discussed later
symbol | Function |
---|---|
* |
define width or decimal point precision |
- |
Display a plus sign ( - ) in front of negative numbers |
+ |
Display a plus sign ( + ) in front of positive numbers |
# |
Displays zero ('0') in front of octal numbers and '0x' or '0X' in front of hexadecimal numbers (depending on whether 'x' or 'X' is used) |
0 |
The displayed numbers are padded with '0' instead of the default space |
% |
%% output a single '%' |
m.n. |
m is the minimum overall width of the display, n is the number of digits after the decimal point (if available) |
: |
The character followed by padding can only be one character. If it is not specified, it will be filled with spaces by default. |
{{}} |
Escape curly braces, %-like output |
5. Number formatting operators
number | Format | output | describe |
---|---|---|---|
3.1415926 | {:.2f} |
3.14 | two decimal places |
3.1415926 | {:+.2f} |
+3.14 | Sign with two decimal places |
-1 | {:+.2f} |
-1.00 | Sign with two decimal places |
2.71828 | {:.0f} |
3 | without decimals |
5 | {:0>2d} |
05 | Number zero padding (pad left, width 2) |
5 | {:x<4d} |
5xxx | Numbers complement x (padding on the right, width is 4) |
10 | {:x<4d} |
10xx | Numbers complement x (padding on the right, width is 4) |
1000000 | {:,} |
1,000,000 | comma-separated number format |
0.25 | {:.2%} |
25.00% | percent format |
1000000000 | {:.2e} |
1.00e + 09 | Exponential notation |
13 | {:10d} |
13 | Align right (default, width 10) |
13 | {:<10d} |
13 | Align left (width is 10) |
13 | {:^10d} |
13 | Center Aligned (width 10) |
Base conversion (take the decimal number 11 as an example)
base | Format | output |
---|---|---|
binary | '{:b}'.format(11) |
1011 |
十进制 | '{:d}'.format(11) |
11 |
八进制 | '{:o}'.format(11) |
13 |
十六进制 | '{:x}'.format(11) |
b |
小写十六进制 | '{:#x}'.format(11) |
0xb |
大写十六进制 | '{:#X}'.format(11) |
0XB |
print('百分比: %d%%' % 23)
print('{}索引值: {{0}}'.format('jun'))
print('{:#x}'.format(9))
print('{:#X}'.format(9))
/*输出结果:
百分比: 23%
jun索引值: {0}
0x9
0X9
*/
6.字符串的内建函数
下列方法实现了string
模块的大部分方法,如下表所示列出了目前字符串内建支持的方法,所有的方法都包含了对Unicode
的支持,有一些甚至是专门用于Unicode
的
方法 | 返回结果 | 描述 |
---|---|---|
'titan'.capitalize() |
Titan | 把字符串的第一个字符大写 |
'hello\tpython'.expandtabs() |
hello python | 把字符串 string 中的 tab 符号转为空格,tab 符号默认的空格数是 8 |
str5.find('irl') |
11 | 检测 str 是否包含在 string 中,如果 beg 和 end 指定范围,则检查是否包含在指定范围内,如果是返回开始的索引值,否则返回-1 |
str5.rfind('irl') |
11 | 同find方法, 从右向左查询 |
str5.index(‘gi’) | 10 | 跟find()方法一样,只不过如果str不在 string中会报一个异常. |
str5.rindex(‘gi’) | 10 | 同index方法, 从右向左查询 |
'jun0929'.isalnum() |
True | 至少有一个字符并且所有字符都是字母或数字则返回 True,否则返回 False |
'titan'.isalpha() |
True | 至少有一个字符并且所有字符都是字母则返回 True,否则返回 False |
u'23e'.isdecimal() |
False | 字符串只包含十进制字符返回True,否则返回False(只针对unicode对象) |
"123456".isdigit() |
True | 字符串只包含数字则返回 True 否则返回 False |
'23e'.islower() |
True | 字符串中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是小写,则返回 True,否则返回 False |
u"23443434"isnumeric() |
True | 字符串中只包含数字字符,则返回 True,否则返回 False(只针对unicode对象) |
" ".isspace() |
True | 字符串中只包含空格,则返回 True,否则返回 False. |
'JING'.isupper() |
True | 字符串中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是大写,则返回 True,否则返回 False |
'-'.join( ['a', 's', 'd'] ) |
a-s-d | 用于将序列中的元素以指定的字符连接生成一个新的字符串 |
'THIS'.lower |
this | 返回将字符串中所有大写字符转换为小写后生成的字符串 |
"88this".lstrip('8') |
this | 返回截掉字符串左边的空格或指定字符后生成的新字符串 |
'this88'.rstrip('8') |
this | 返回截掉字符串右边的空格或指定字符后生成的新字符串 |
max('python') |
z | 返回字符串中最大的字母 |
min('python') |
h | 返回字符串中最小的字母 |
'https://www.titanjun.top'.partition('://') |
(‘https’, ‘://’, ‘www.titanjun.top’) | 返回一个3元的元组,第一个为分隔符左边的子串,第二个为分隔符本身,第三个为分隔符右边的子串 |
'this'.startswith('th', 1, 4) |
False | 检查字符串在制定范围内是否是以指定子字符串开头 |
"0jun0".strip('0') |
jun | 返回移除字符串头尾指定的字符生成的新字符串 |
'Python'.swapcase() |
pYTHON | 返回大小写字母转换后生成的新字符串 |
'hello python'.title() |
Hello Python | 返回所有单词都是以大写开始 |
'jun'.upper() |
JUN | 返回小写字母转为大写字母的字符串 |
除了以上方法外还有下列重要方法
6-1. count()方法
返回子字符串在字符串中出现的次数
str.count(sub, start= 0,end=len(string))
//使用
print('hello world'.count('l', 1, 8))
print('hello world'.count('l'))
//输出:
2
3
- 参数
sub
– 搜索的子字符串start
– 字符串开始搜索的位置。默认为第一个字符,第一个字符索引值为0。end
– 字符串中结束搜索的位置。字符中第一个字符的索引为 0。默认为字符串的最后一个位置。
6-2. center()方法
返回一个原字符串居中,并使用空格填充至长度 width 的新字符串。默认填充字符为空格
str.center(width, fillchar)
//使用
>>> str = 'titan'
>>> str.center(8, '-')
'--titan---'
>>> str.center(9)
' titan '
>>>
- 不提供
fillchar
参数则默认为空格 - 当
width
参数小于等于原字符串的长度时,原样返回 - 无法使左右字符数相等时候,左侧字符会比右侧少 1
6-3. encode()方法
以 encoding 指定的编码格式编码字符串。errors参数可以指定不同的错误处理方案
str.encode(encoding='UTF-8',errors='strict')
//示例
'titan'.encode('UTF-8','strict')
//输出: b'titan'
encoding
– 要使用的编码,如”UTF-8”。errors
– 设置不同错误的处理方案。默认为strict
,意为编码错误引起一个UnicodeError
。 其他可能得值有ignore
,replace
,xmlcharrefreplace
,backslashreplace
以及通过codecs.register_error()
注册的任何值。
6-4. endswith()方法
用于判断字符串是否以指定后缀结尾,如果以指定后缀结尾返回True,否则返回False
str.endswith(suffix[, start[, end]])
//使用示例
str5 = 'her is my girl friend haha!!'
print(str5.endswith('!!'))
print(str5.endswith('ha', 0, len(str5) - 2))
//输出结果: 都是True
suffix
– 该参数可以是一个字符串或者是一个元素start
– 字符串中的开始位置, 可不传end
– 字符中结束位置, 可不传
6-5. ljust() 和 rjust()方法
ljust()
: 返回一个原字符串左对齐,并使用空格填充至指定长度的新字符串。如果指定的长度小于原字符串的长度则返回原字符串rjust()
: 返回一个原字符串右对齐- 参数
width
– 指定字符串长度。fillchar
– 填充字符,默认为空格
str.ljust(width[, fillchar])
str.rjust(width[, fillchar])
//测试用例
str = "this is string example....wow!!!";
print str.ljust(50, '0');
print str.rjust(50, '0');
//输出:
this is string example....wow!!!000000000000000000
000000000000000000this is string example....wow!!!
6-6. replace()方法
返回字符串中的 old(旧字符串) 替换成 new(新字符串)后生成的新字符串,如果指定第三个参数max,则替换不超过 max 次
str.replace(old, new[, max])
//测试
str = 'Python is a good language!'
print(str7.replace('o', 'i', 2))
//输出:
Pythin is a giod language!
6-7. split()方法
通过指定分隔符对字符串进行切片,如果参数 num 有指定值,则仅分隔 num 个子字符串
str.split(str="", num=string.count(str))
//测试
str7 = 'Python is a good language!'
print(str7.split(' '))
print(str7.split(' ', 3))
//输出:
['Python', 'is', 'a', 'good', 'language!']
['Python', 'is', 'a', 'good language!']
6-8. splitlines()方法
按照行('\r', '\r\n', \n'
)分隔,返回一个包含各行作为元素的列表,如果参数 keepends 为 False,不包含换行符,如果为 True,则保留换行符
str.splitlines([keepends])
//测试
str8 = 'ab c\n\nde fg\rkl\r\n'
print(str8.splitlines())
str9 = 'ab c\n\nde fg\rkl\r\n'
print(str9.splitlines(True))
//输出:
['ab c', '', 'de fg', 'kl']
['ab c\n', '\n', 'de fg\r', 'kl\r\n']
- 对于
Python
语言, 我也正在努力学习中, 文中如有不足之处, 还望多多指教 - 测试代码详见 GitHub地址
- 后期会持续更新相关文章, 未完待续…