• Details of Python data types 02
  • Above,Python data types 01In the main introductionPythonSome commonly used data types in
  • This article mainly introduces somePythonSome commonly used modules in

A. Number B. Number C. Number

  • PythonThe functions commonly used in mathematical operations are basically inmathModule,cmathIn the module.
  • mathThe module provides a number of mathematical operations on floating point numbers.
  • cmathThe module contains functions for complex number operations.
  • cmathModule functions andmathThe module functions are basically the same, the difference iscmathModules operate on complex numbers,mathModules do mathematical operations.
  • In order to usemathcmathThe function must first enter:
import math

# or
import cmath
Copy the code

1. Python mathematical constants

Three mathematical constants are defined in the Math module

# Natural constant e
e = 2.718281828459045
# PI, usually represented by π
pi = 3.141592653589793
# 2 PI.
tau = 6.283185307179586
Copy the code

2. Python trigonometric functions

To access it directly, you need to import the Math module and then invoke methods through the Math static object

function describe
acos(x) Returns the arccosine radian value of x.
asin(x) Returns the arcsine radian value of x.
atan(x) Returns the arctangent radian value of x.
atan2(y, x) Returns the arctangent of the given X and Y coordinates.
cos(x) Returns the cosine of x radians.
hypot(x, y) Returns the Euclidean normsqrt(x*x + y*y).
sin(x) The sine of x radians returned.
tan(x) Returns the tangent of x radians.
degrees(x) Convert radians to angles, such as degrees(math.pi/2), and return 90.0
radians(x) Convert the Angle to radians

3.Python mathematical functions

function Return value (Description)
abs(x) Returns the absolute value of a number, such as abs(-12) returns 12
ceil(x) Returns an integer (rounded up from decimals) of a number, such as math.ceil(4.1) returns 5 and math.ceil(4.0) returns 4
cmp(x, y) ifx < yReturns -1 ifx == yReturns 0 ifx > yReturn 1; (Python is deprecated in 3.x)
exp(x) Returns e to the x power, as math.exp(2) returns 7.38905609893065
fabs(x) Returns the absolute value of a number, as inmath.fabs(-10)Return 10.0
floor(x) Returns the rounded integer of the number (rounded down the decimal), as math.floor(4.9) returns 4
log(x) Such asmath.log(math.e)Back to 1.0,Math. The log (100, 10)Return 2.0
log10(x) Returns the logarithm of x in base 10, as inmath.log10(100)Return 2.0
max(x1, x2,…) Returns the maximum value of 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 and decimal parts of x (in tuple form). Both parts have the same numeric symbol as x. The integer part is represented as floating-point; Such as:Math. Modf (99.09), return (0.09000000000000341, 99.0)
pow(x, y) x**yThe evaluated value.
round(x [,n]) Returns the rounded value of the floating point number x, if n is given, representing the number of digits rounded to the decimal point; For example round(90.09, 1) output :90.1; Such as:Round (90.09)Output: 90
sqrt(x) Return the square root of the number x, as in:math.sqrt(4)Return 2.0
  • Among themabs()fabs()The difference between
    • abs()Is a built-in function, andfabs()inmathDefined in the module.
    • fabs()Function only applies tofloatandintegerType, andabs()It also applies to complex numbers

4. Python random number functions

  • Random numbers can be used in mathematics, games, security and other fields, and are often embedded in algorithms to improve the efficiency of algorithms and improve the security of programs.
  • Random number functions need to be importedrandomModule, and then throughrandomStatic objects call function methods
  • PythonContains the following common random number functions:

4-1. choice

Selects a random element from the elements of a sequence (tuple, list, string)

import random

random.choice( seq  )

# Test cases
# Select a random element from the elements of the sequence
print(random.choice((1.3.5.2)))
print(random.choice([1.2.3.4]))
# Return a random character
print(random.choice("titanjun"))
Copy the code

4-2. randrange

Returns a random number in the specified increasing cardinality set. The default cardinality default is 1 and the default type is int

randrange(self, start, stop=None, step=1, _int=int)
Copy the code
  • parameter
    • start— Specifies the start value of the range, contained in the range.
    • stop— Specifies the end value in the range, not included in the range.
    • step— Specifies the increment base
Output # 100Print (random. Randrange (100, 1000, 2))Copy the code

4-3. random

A randomly generated real number in the range [0,1]

print(random.random())
Copy the code

4-4. seed

This function returns no value and changes the seed of the random number generator to generate the same random number

random.seed(5)
print(random.random())
random.seed()
print(random.random())
Copy the code

4-5. shuffle

  • Sort all elements of the list randomly, with no return value
  • Tuples cannot be rearranged because they do not support secondary assignment
Order all elements of the sequence randomly
list1 = [1.2.3.4]
random.shuffle(list1)
print(list1)
Copy the code

4-6. uniform

  • Generates a random real number in the range [x, y]
  • Parameters:
    • X – The minimum value of a random number, including the value.
    • Y — the maximum number of random numbers, excluding this value.
print(random.uniform(2.5))
Copy the code

2. String

In this article, we will introduce some basic functions and syntax used in character creation

1. innot in

Checks whether the 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 inCopy the code

2. String formatting

Format other types of data to return as strings separated by %

symbol describe
%c Format characters and their ASCII codes
%s Formatted string
%d Formatted integer
%u Format an unsigned integer
%o Format an unsigned octal number
%x Format an unsigned hexadecimal number
%X Formatted unsigned hexadecimal number (uppercase)
%f Format a floating-point number that specifies the precision after the decimal point
%e Format floating point numbers with scientific notation
%E Same as %e, uses scientific notation to format floating-point numbers
%g Short for %f and %e
%G Short for %f and %E
%p Format the address of a variable with a hexadecimal number

use

Print ('che is %d' % 19) print('che is %d' % 19) print('che is %d' % 19)Copy the code

3. str.format()function

  • Python2.6In the beginning, we added a function to format stringsstr.format(), which enhances string formatting. Basic grammar is passed{}:To replace the old one%
  • formatFunctions can take unlimited arguments and positions out of order.

Simple to use

# format function # does not set the specified position, Format ('hello', 'python') print(str1) # str2 = '{0}{1}'. Format (' python', 'python') print(str1) # str2 = '{0}{1}'. Format (' python', 'python') Str3 = '{1} {0} {1}'. Format ('hello', 'che') print(str3) print(' name ', 'age ') {age} ". The format (name = 'che', the age = 18)) # set dictionary parameter dic = {' name ':' jun ', 'age: 20} print (" name: {name}, age: {the age} ". The format (dic) * *) # set list parameters list0 = [' Titan, 20] print (" name: [0] {0}, age: {0[1]}". Format (list0)) /* Output Hello Python Python string che Hello che Name: che, Age: 18 Name: Jun, age: 20 Name: Titan, age: 20 */Copy the code

4. Formatting operator auxiliary instructions

More on how to use the related operators later

symbol function
* Define width or decimal precision
- Display a plus sign (-) before negative numbers
+ Display a plus sign (+) before a positive number
# Display zero before octal numbers (‘0’) and either ‘0x’ or ‘0x’ before hexadecimal numbers (depending on whether ‘x’ or ‘x’ is used)
0 The number displayed is preceded by a ‘0’ instead of the default space
% % %Output a single ‘%’
m.n. M is the minimum total width to display and n is the number of decimal places (if available)
: The character followed by padding can be only one character. If this parameter is not specified, the padding is a space by default
{{}} Escape braces, similar to % output

5. Number formatting operator

digital format The output describe
3.1415926 {:.2f} 3.14 Keep two decimal places
3.1415926 {:+.2f} + 3.14 The sign preserves two decimal places
– 1 {:+.2f} 1.00 The sign preserves two decimal places
2.71828 {:.0f} 3 With no decimal
5 {:0>2d} 05 Numeric zeroing (padding left, width 2)
5 {:x<4d} 5xxx Number fill x (fill right side, width 4)
10 {:x<4d} 10xx Number fill x (fill right side, width 4)
1000000 {:} 1000000 Number format separated by commas
0.25 } {: 2% 25.00% Percentage format
1000000000 {:.2e} 1.00 e+09 Index notation
13 {:10d} 13 Right aligned (default, width 10)
13 {:<10d} 13 Left aligned (width 10)
13 {:^10d} 13 Middle alignment (width 10)

Base conversion (using the decimal number 11 as an example)

Into the system format The output
binary '{:b}'.format(11) 1011
The decimal system '{:d}'.format(11) 11
octal '{:o}'.format(11) 13
hexadecimal '{:x}'.format(11) b
Lowercase hexadecimal '{:#x}'.format(11) 0xb
Uppercase hexadecimal '{:#X}'.format(11) 0XB
Print (' % : % d % % % 23) print (' {} index values: {{0}} '. The format (' jun) print (' {: # x} '. The format (9)) print (' {: # x} '. The format (9)) / * output: Jun index value: {0} 0x9 0x9 */Copy the code

6. Built-in functions for strings

The following methods implement most of the string module’s methods. The following table lists the methods currently supported in strings. All of these methods contain Unicode support, and some are even unicode-specific

methods Returns the result describe
'titan'.capitalize() Titan Capitalize the first character of the string
'hello\tpython'.expandtabs() hello python Convert the TAB character in string to a space. The default TAB character is 8 Spaces
str5.find('irl') 11 Check if STR is contained in string, if beg and end specify a range, if it is the starting index, otherwise -1
str5.rfind('irl') 11 Same as find, search from right to left
str5.index(‘gi’) 10 Same as the find() method, except that an exception is raised if STR is not in string.
str5.rindex(‘gi’) 10 Same as index method, from right to left query
'jun0929'.isalnum() True Returns True if there is at least one character and all characters are letters or numbers, False otherwise
'titan'.isalpha() True Returns True if there is at least one character and all characters are letters, False otherwise
u'23e'.isdecimal() False Returns True for string containing only decimal characters, False otherwise (for Unicode objects only)
"123456".isdigit() True Returns True if the string contains only numbers; False otherwise
'23e'.islower() True Returns True if the string contains at least one case-sensitive character and all of these characters are lowercase, False otherwise
u"23443434"isnumeric() True Return True if string contains only numeric characters, False otherwise (for Unicode objects only)
" ".isspace() True Returns True if the string contains only Spaces, False otherwise.
'JING'.isupper() True Returns True if the string contains at least one case-sensitive character and all of these characters are uppercase, False otherwise
'-'.join( ['a', 's', 'd'] ) a-s-d Use to concatenate the elements in a sequence to generate a new string
'THIS'.lower this Returns the string generated by converting all uppercase characters in a string to lowercase
"88this".lstrip('8') this Returns a new string generated by cutting off the space to the left of the string or the specified character
'this88'.rstrip('8') this Returns a new string generated by cutting off Spaces or specified characters to the right of the string
max('python') z Returns the largest letter in the string
min('python') h Returns the smallest letter in the string
'https://www.titanjun.top'.partition('://') (‘https’, ‘://’, ‘www.titanjun.top’) Returns a 3-tuple, the first being the substring to the left of the delimiter, the second being the delimiter itself, and the third being the substring to the right of the delimiter
'this'.startswith('th', 1, 4) False Checks if the string begins with the specified substring in the specified range
"0jun0".strip('0') jun Returns a new string generated by removing the characters specified at the beginning and end of the string
'Python'.swapcase() pYTHON Returns a new string generated after the case conversion
'hello python'.title() Hello Python Returns that all words begin in uppercase
'jun'.upper() JUN Returns a string converted from lowercase to uppercase

In addition to the above methods, there are the following important methods

6-1. The count () method

Returns the number of occurrences of a substring in a string

STR. Count (sub, start= 0,end=len(string)) print('hello world'. Print ('hello world'. Count ('l')Copy the code
  • parameter
    • sub— Substring of the search
    • start— The position where the string begins to search. Default is the first character, the first character index value is 0.
    • end— The position in the string where the search ends. The index of the first character in a character is 0. Defaults to the last position in the string.

6-2. Center () method

Returns a centered string filled with Spaces to a new string of length width. The default padding character is space

STR. Center (width, fillchar) / / use the > > > STR = 'Titan' > > > STR. The center (8, '-') '- Titan -' > > > STR. The center (9) 'Titan' > > >Copy the code
  • Does not providefillcharThe default parameter is space
  • whenwidthIf the argument is less than or equal to the length of the original string, it is returned as is
  • When the left and right characters cannot be equal, the left character is 1 less than the right character

6 – (3) encode () method

Encodes a string in the encoding format specified in encoding. The errors argument can specify different error handling schemes

Str.encode (encoding=' utF-8 ',errors='strict') // example 'Titan '.encode('UTF-8','strict') // output: b' Titan'Copy the code
  • encoding— The encoding to use, such as “UTF-8”.
  • errorsSet different error handling schemes. The default isstrict, meaning a coding error causes aUnicodeError. Other possible values areignore.replace.xmlcharrefreplace.backslashreplaceAnd bycodecs.register_error()Any value registered.

6-4. Endswith () method

Used to determine whether the string ends with the specified suffix. Returns True if the string ends with the specified suffix, False otherwise

Str.endswith (suffix[, start[, end]]) // Example str5 = 'Her is my girl friend!! ' print(str5.endswith('!! ')) print(str5.endswith('ha', 0, len(str5) -2)Copy the code
  • suffixThis parameter can be a string or an element
  • start— The start position of the string, not passed
  • end— The end position of the character, not passed

6-5. Ljust () and rjust() methods

  • ljust(): Returns a left-aligned string filled with Spaces to a new string of specified length. Returns the string if the specified length is less than the length of the original string
  • rjust(): Returns a right-aligned string
  • parameter
    • width— Specifies the length of the string.
    • fillchar— Padding character, default is space
str.ljust(width[, fillchar])
str.rjust(width[, fillchar])

// Test case
str = "this is string example.... wow!!!";
print str.ljust(50.'0');
print str.rjust(50.'0');

/ / output:
thisis string example.... wow!!!000000000000000000
000000000000000000thisis string example.... wow!!!Copy the code

6-6. The replace () method

Returns a new string generated by replacing old with new in a string, Max times if the third argument Max is specified

Replace (old, new[, Max]) // Test STR = 'Python is a good language! 'print(str7.replace('o',' I ', 2)) // Print: Pythin is a giod language!Copy the code

6-7. The split () method

Slicing a string by specifying a delimiter, only the num substring is delimited if the num argument has a specified value

Str.split (STR ="", num=string.count(STR)) // test str7 = 'Python is a good language! 'print (str7. Split (')) print (str7. Split (", 3)) / / output: ['Python', 'is', 'a', 'good', 'language!'] ['Python', 'is', 'a', 'good language!']Copy the code

6-8. Splitlines () method

Returns a list of rows as elements separated by lines (‘\r’, ‘\r\n’, \n’), with no newlines if keepends is False, and newlines if True

Str8 = 'ab c\n\nde fg\ RKL \r\n' print(str8.splitlines()) str9 = 'ab c\n\nde fg\ RKL \r\n' str8.splitlines([keepends]) str8 = 'ab c\n\nde fg\ RKL \r\n' Print (str9. Splitlines (True)) / / output: [' ab c ', ' ', 'DE fg', 'kl] [' ab c \ n', '\ n', 'DE fg \ r', 'kl \ r \ n']Copy the code
  • forPythonLanguage, I am also trying to learn, if there is any inadequacy in the article, I hope you can give me more advice
  • See GitHub address for the test code
  • Later will continue to update the relevant articles, to be continued…