a >> 2 The output result is 15, binary Explanation: 0000 1111 |
|
python logical operators
##Operator | Logical expression Formula | Description | Example |
and | x and y | Boolean "AND" - if x If False, x and y return False, otherwise it returns the calculated value of y. | (a and b) returns 20. |
or | x or y | Boolean "or" - if x is True, it returns True, otherwise it returns the calculated value of y. | (a or b) returns 10. |
not | not x | Boolean "not" - If x is True, returns False. If x is False, it returns True. | not(a and b) returns False |
Member operators of python
##Operator | Description | Example |
in | Returns True if the value is found in the specified sequence, False otherwise. | x is in the y sequence, returns True if x is in the y sequence. |
not in | Returns True if the value is not found in the specified sequence, False otherwise. | x is not in the y sequence, returns True if x is not in the y sequence. |
Priority of python
** |
Index (highest priority) |
##~ + - | Bitwise flip , unary plus sign and minus sign (the last two methods are named +@ and -@) |
* / % // | Multiplication, division, modulo Sum and division |
+ - | Addition and subtraction |
>> 7ffcc8ef8bb6ba8e5ca4efdcfabb8b01 >= | Comparison operator |
c5257ed5daca028f2c17ced65b96e97a y returns 1
exp(x) |
Returns the x power of e (ex), such as math.exp(1) returns 2.718281828459045 |
fabs(x) |
Returns the absolute value of the number, such as math.fabs(-10) returns 10.0 |
floor(x) |
Return the rounded integer of the number, such as math.floor(4.9) returns 4 |
log(x) |
For example, math.log(math.e) returns 1.0, math.log(100,10) returns 2.0 |
log10(x) |
Returns the logarithm of x with base 10 as the base, such as math.log10( 100) Return 2.0 |
max(x1, x2,...) |
Returns the maximum value of the given parameter, and the parameter can be a sequence. |
min(x1, x2,...) |
Returns the minimum value of the given parameter, which can be a sequence. |
modf(x) |
Returns the integer part and decimal part of x. The numerical signs of the two parts are the same as x, and the integer part is expressed in floating point type. |
pow(x, y) |
x**y Value after operation. |
round(x [,n]) |
Returns the rounded value of the floating point number x. If the n value is given, it represents the number of digits rounded to the decimal point. . |
sqrt(x) |
Returns the square root of the number x. The number can be negative and the return type is real number. For example, math.sqrt(4) returns 2+0j |
python random 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.
Python contains the following commonly used random number functions:
Function |
Description |
choice (seq) |
Randomly select an element from the elements of the sequence, such as random.choice(range(10)), randomly select an integer from 0 to 9. |
randrange ([start,] stop [,step]) |
Get a random number from the set in the specified range, incremented by the specified base, the base is default The value is 1 |
random() |
Randomly generates the next real number, which is in the range [0,1). |
seed([x]) |
Change the seed of the random number generator. If you don't understand the principle, you don't have to set the seed specifically, Python will choose the seed for you. |
shuffle(lst) |
Randomly sort all elements of the sequence |
uniform(x, y) | Randomly generate the next real number, which is in the range [x, y]. |
Trigonometric functions of python
Number |
Description |
|
##acos(x) | Return the arc cosine radians value of x. |
|
asin(x) | Returns the arcsine radians value of x. | |
atan(x) | Returns the arctangent radian value of x. |
|
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 value of x radians. |
|
|
tan(x)
Returns the tangent of x in radians. |
|
degrees(x) |
Convert radians to degrees, such as degrees(math.pi/2), return 90.0 |
|
radians(x) |
Convert angles to radians |
|
Python's built-in string functions
##Method
|
Description
|
string.capitalize()
|
Put the first string uppercase characters
|
##string.center(width) | Returns an original string centered and filled with spaces New string to length width |
##string.count(str, beg=0, end=len(string))
Returns the number of times str appears in string. If beg or end is specified, returns the number of times str appears in the specified range. |
|
string.decode(encoding='UTF-8', errors='strict')
Decode string in the encoding format specified by encoding. If an error occurs, a ValueError exception will be reported by default, unless errors specify 'ignore' or 'replace' |
string.encode(encoding='UTF-8', errors='strict') |
The encoding specified by encoding Format encoding string, if an error occurs, a ValueError exception will be reported by default, unless errors specify 'ignore' or 'replace' |
string.endswith( obj, beg=0, end=len(string)) |
Check whether the string ends with obj. If beg or end is specified, check whether the specified range ends with obj. End, if yes, return True, otherwise return False. |
##string.expandtabs(tabsize=8)
|
Convert the tab symbol in the string string to spaces. The default number of spaces for the tab symbol is 8.
|
##string.find(str, beg=0, end=len(string)) | Check whether str is included in string. If beg and end specify the range, check whether it is included in the specified range. If it is, return the starting index value, otherwise return -1 |
string.index(str, beg=0, end=len(string))
| The same as the find() method, only However, if str is not in string, an exception will be reported. |
string.isalnum() |
Returns ## if string has at least one character and all characters are letters or numbers #Return True, otherwise return False
|
string.isalpha()
|
If string has at least one character and all characters are letters, return True, Otherwise, return False
|
##string.isdecimal() | Returns True if string contains only decimal digits, otherwise returns False. |
##string.isdigit()
If string only contains numbers, return True otherwise return False. |
| ##string.islower()
Returns True if string contains at least one case-sensitive character and all of these (case-sensitive) characters are lowercase, otherwise False |
| string.isnumeric()
If the string contains only numeric characters, return True, otherwise return False |
##string.isspace()
|
If the string contains only spaces, return True, otherwise return False.
|
##string.istitle()
| Returns True if string is titled (see title()), otherwise returns False |
string.isupper( ) | Returns True if string contains at least one case-sensitive character and all these (case-sensitive) characters are uppercase, otherwise it returns False |
string.join(seq)
| Using string as the separator, join all elements in seq (String representation) merged into a new string |
string.ljust(width) | Return A new string that aligns the original string to the left and pads it with spaces to length width |
##string.lower()Convert all uppercase characters in string to lowercase. |
##string.lstrip()
| Truncate the spaces to the left of string
|
##string.maketrans(intab, outtab]) | maketrans( ) method is used to create a conversion table for character mapping. For the simplest calling method that accepts two parameters, the first parameter is a string representing the character that needs to be converted, and the second parameter is also the string representing the target of conversion. |
max(str) | Returns the largest letter in the string str .
|
min(str) | Returns the smallest letter in the string str .
|
##string.partition(str)
A bit like find() and split( ), starting from the first position where str appears, divide the string string into a 3-element tuple (string_pre_str, str, string_post_str). If string does not contain str, then string_pre_str == string. |
string.replace(str1, str2, num=string.count(str1)) |
Replace str1 in string with str2. If num is specified, the replacement will not exceed num times. |
string.rfind(str, beg=0,end= len(string) ) |
Similar to the find() function, but starting from the right. |
string .rindex(str, beg=0,end=len(string)) |
Similar to index(), but starts from the right. |
string.rjust(width) |
Returns a new string with the original string right-aligned and padded with spaces to length width |
string.rpartition(str) |
Similar to the partition() function, but starts searching from the right. |
string.rstrip() |
Remove string spaces at the end of the string. |
string.split(str="", num=string.count(str)) |
Use str as the delimiter to slice string. If num has a specified value, only num substrings will be separated. |
##string.splitlines(num=string.count( '\n'))
|
Separated by row, return a list containing each row as an element. If num is specified, only num rows will be sliced.
|
string.startswith(obj, beg=0,end=len(string))
|
Check whether the string starts with obj, if so, return True, otherwise returns False. If beg and end specify values, check within the specified range.
|
string.strip([obj]) |
Execute lstrip() and rstrip() on string
|
##string.swapcase() | Reverse case in string |
string.title() |
Returns a "titled" string, that is, all words start with uppercase letters, and the remaining letters are lowercase (see istitle()) |
string.translate(str, del="") |
Convert string according to the table (containing 256 characters) given by str Characters,
Put the characters to be filtered out in the del parameter
|
string.upper() |
Convert the lowercase letters in string to uppercase
|
string.zfill(width) |
The return length is The string of width, the original string string is right-aligned, and the front is filled with 0 |
string.isdecimal() |
The isdecimal() method checks whether a string contains only decimal characters. This method only exists for unicode objects. |
Python's List function
##Serial number | Function |
1 | cmp(list1, list2)Compare the elements of two lists
|
2 | len(list)Number of list elements
|
3 | max(list)Returns the maximum value of list elements
|
4 | min(list)Returns the minimum value of the list element
|
5 | list(seq)Convert tuple to list
|
Python contains the following methods:
Serial number |
Method |
1 |
list.append(obj) Add a new object at the end of the list |
2 |
list.count(obj) Count the number of elements in the list The number of occurrences in |
3 |
list.extend(seq) Append multiple values from another sequence at the end of the list at once (use a new list Expand the original list) |
4 |
list.index(obj) Find the index position of the first matching item of a value from the list |
5 |
list.insert(index, obj) Insert object into the list |
6 |
list.pop(obj=list[-1]) Remove an element in the list (the last element by default) and return the value of the element |
7 |
list.remove(obj) Remove the first occurrence of a value in the list |
8 |
list.reverse () Elements in the reverse list |
9 |
list.sort([func]) Sort the original list |
Python tuples’ built-in functions
The Python tuple contains the following built-in functions
Serial number |
Method and description |
1 |
cmp(tuple1, tuple2) Compare two tuple elements. |
2 |
len(tuple) Calculate the number of tuple elements. |
3 |
max(tuple) Returns the maximum value of the element in the tuple. |
4 |
min(tuple) Returns the minimum value of the element in the tuple. |
5 |
tuple(seq) Convert the list to a tuple. |
Dictionary built-in functions & methods
Python dictionary contains the following built-in functions:
Serial number |
Function and description |
1 |
cmp(dict1, dict2) Compares two dictionary elements. |
2 |
len(dict) Calculate the number of dictionary elements, that is, the total number of keys. |
3 |
str(dict) Output the printable string representation of the dictionary. |
4 |
type(variable) Returns the input variable type. If the variable is a dictionary, returns the dictionary type. |
Python dictionary contains the following built-in methods:
Serial number |
Function and description |
1 |
radiansdict.clear() Delete all elements in the dictionary |
2 |
radiansdict.copy() Return a dictionary Copy |
3 |
radiansdict.fromkeys() Create a new dictionary, using the elements in the sequence seq as the keys of the dictionary, and val is the value corresponding to all keys in the dictionary Initial value |
4 |
radiansdict.get(key, default=None) Returns the value of the specified key, if the value is not in the dictionary, returns the default value |
5 |
radiansdict.has_key(key) Returns true if the key is in the dictionary dict, otherwise returns false |
6 |
radiansdict.items() Returns a traversable (key, value) tuple array as a list |
7 |
radiansdict. keys() Returns all the keys of a dictionary in a list |
8 |
radiansdict.setdefault(key, default=None) and get() Similar, but if the key does not exist in the dictionary, the key will be added and the value will be set to default |
9 |
radiansdict.update(dict2) Put The key/value pairs of dictionary dict2 are updated into dict |
10 |
radiansdict.values() Return all values in the dictionary as a list |
Python 日期和时间
thon 程序能用很多方式处理日期和时间,转换日期格式是一个常见的功能。
Python 提供了一个 time 和 calendar 模块可以用于格式化日期和时间。
时间间隔是以秒为单位的浮点小数。
每个时间戳都以自从1970年1月1日午夜(历元)经过了多长时间来表示。
Python 的 time 模块下有很多函数可以转换常见日期格式。如函数time.time()用于获取当前时间戳, 如下实例:
#!/usr/bin/python# -*- coding: UTF-8 -*-import time; # 引入time模块ticks = time.time()print "当前时间戳为:", ticks 以上实例输出结果: 当前时间戳为: 1459994552.51 时间戳单位最适于做日期运算。但是1970年之前的日期就无法以此表示了。太遥远的日期也不行,UNIX和Windows只支持到2038年。
什么是时间元组?
很多Python函数用一个元组装起来的9组数字处理时间:
Serial number |
Field |
Value |
0 |
4-digit year |
2008 |
1 |
month |
1 to 12 |
2 |
日 |
1 to 31 |
3 |
hours |
0 to 23 |
4 |
Minutes |
0 to 59 |
5 |
Seconds |
0 to 61 (60 or 61 is a leap second) |
6 |
Day of the week |
0 to 6 (0 is Monday) |
7 |
Day of the year |
1 to 366 (Julian calendar) |
8 |
Daylight Saving Time |
-1, 0, 1, -1 is the flag to determine whether it is daylight saving time |
The above is the struct_time tuple. This structure has the following properties:
Serial number |
Attribute |
Value |
0 |
tm_year | 2008 |
1 |
tm_mon |
1 to 12 |
2 |
tm_mday |
1 to 31 |
3 |
tm_hour |
0 to 23 |
4 |
tm_min |
0 to 59 |
5 |
tm_sec |
0 to 61 ( 60 or 61 is a leap second) |
6 |
tm_wday |
0 to 6 (0 is Monday) |
7 |
tm_yday |
1 to 366 (Julian calendar) |
8 |
tm_isdst |
-1, 0, 1, -1 are flags to determine whether it is daylight saving time |
获取当前时间
从返回浮点数的时间辍方式向时间元组转换,只要将浮点数传递给如localtime之类的函数。 #!/usr/bin/python# -*- coding: UTF-8 -*-import time
localtime = time.localtime(time.time())print "本地时间为 :", localtime 以上实例输出结果: 本地时间为 : time.struct_time(tm_year=2016, tm_mon=4, tm_mday=7, tm_hour=10, tm_min=3, tm_sec=27, tm_wday=3, tm_yday=98, tm_isdst=0)
获取格式化的时间
你可以根据需求选取各种格式,但是最简单的获取可读的时间模式的函数是asctime(): #!/usr/bin/python# -*- coding: UTF-8 -*-import time
localtime = time.asctime( time.localtime(time.time()) )print "本地时间为 :", localtime 以上实例输出结果: 本地时间为 : Thu Apr 7 10:05:21 2016
格式化日期
我们可以使用 time 模块的 strftime 方法来格式化日期,: time.strftime(format[, t]) #!/usr/bin/python# -*- coding: UTF-8 -*-import time# 格式化成2016-03-20 11:45:39形式print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) # 格式化成Sat Mar 28 22:24:24 2016形式print time.strftime("%a %b %d %H:%M:%S %Y", time.localtime())
# 将格式字符串转换为时间戳a = "Sat Mar 28 22:24:24 2016"print time.mktime(time.strptime(a,"%a %b %d %H:%M:%S %Y")) 以上实例输出结果: 2016-04-07 10:25:09Thu Apr 07 10:25:09 20161459175064.0 python中时间日期格式化符号:
获取某月日历
Calendar模块有很广泛的方法用来处理年历和月历,例如打印某月的月历: #!/usr/bin/python# -*- coding: UTF-8 -*-import calendar
cal = calendar.month(2016, 1)print "以下输出2016年1月份的日历:"print cal; 以上实例输出结果: 以下输出2016年1月份的日历:
January 2016Mo Tu We Th Fr Sa Su
1 2 3
4 5 6 7 8 9 1011 12 13 14 15 16 1718 19 20 21 22 23 2425 26 27 28 29 30 31
Time 模块
Time 模块包含了以下内置函数,既有时间处理相的,也有转换时间格式的:
Serial number |
Function and description |
1 |
time.altzone Return to Greenway The offset in seconds for the western daylight saving time zone. Negative values are returned if the area is east of Greenwich (such as Western Europe, including the UK). Available only in regions where daylight saving time is enabled. |
2 |
time.asctime([tupletime]) Accepts a time tuple and returns a readable form of "Tue Dec 11 18:07: 14 2008" (Tuesday, December 11, 2008 18:07:14) is a 24-character string. |
3 |
time.clock( ) Returns the current CPU time in seconds calculated as a floating point number. It is used to measure the time consumption of different programs and is more useful than time.time(). |
4 |
time.ctime([secs]) The function is equivalent to asctime(localtime(secs)). No parameters are given, which is equivalent to asctime() |
5 |
time.gmtime([secs]) Receives the timeout (the number of floating point seconds elapsed since the 1970 epoch) and returns Greenwich astronomical time The time tuple under t. Note: t.tm_isdst is always 0 |
6 |
time.localtime([secs]) Receive time (floating point seconds elapsed after 1970 epoch number) and returns the time tuple t in local time (t.tm_isdst can be 0 or 1, depending on whether the local time is daylight saving time). |
7 |
time.mktime(tupletime) Accepts a time tuple and returns the timeout (the number of floating point seconds elapsed since epoch 1970). |
8 |
time.sleep(secs) Delay the running of the calling thread, secs refers to the number of seconds. |
9 |
time.strftime(fmt[,tupletime]) Receives a time tuple and returns the local time as a readable string in a format determined by fmt. |
10 |
time.strptime(str,fmt='%a %b %d %H:%M:%S %Y') According to The format of fmt parses a time string into a time tuple. |
11 |
time.time( ) Returns the timestamp of the current time (the number of floating-point seconds elapsed since epoch 1970). |
12 |
time.tzset() Reinitialize time-related settings according to the environment variable TZ. |
The Time module contains the following two very important attributes:
Serial Number |
Attribute And description |
1 |
time.timezone The property time.timezone is the local time zone (without daylight saving time) distance from Greenwich Offset seconds (>0, Americas; <=0 most of Europe, Asia, Africa). |
2 |
time.tzname The attribute time.tzname contains a pair of strings that vary depending on the situation, namely The local time zone name with and without daylight saving time. |
Calendar module
The functions of this module are all calendar-related, such as printing the character calendar of a certain month.
Monday is the default first day of the week, and Sunday is the default last day. To change the settings, you need to call the calendar.setfirstweekday() function. The module contains the following built-in functions:
Serial number |
Function and description |
1 |
calendar.calendar(year, w=2,l=1,c=6) Returns a year calendar in multi-line string format, with 3 months per line and an interval of c. Daily width interval is w characters. The length of each line is 21* W+18+2* C. l is the number of lines per week. |
2 |
calendar.firstweekday( ) Returns the setting of the current weekly starting day. By default, 0 is returned when the caendar module is first loaded, which is Monday. |
3 |
calendar.isleap(year) returns True if it is a leap year, otherwise false. |
4 |
calendar.leapdays(y1,y2) Returns the total number of leap years between Y1 and Y2. |
5 |
calendar.month(year,month,w=2,l=1) Returns a multi-line string The calendar format is year and month, with two rows of titles and one row for each week. Daily width interval is w characters. The length of each line is 7* w+6. l is the number of lines per week. |
6 |
calendar.monthcalendar(year,month) Returns a single-level nested list of integers. Each sublist holds an integer representing a week. Dates outside Year, month, and month are all set to 0; days within the range are represented by the day of the month, starting from 1. |
7 |
calendar.monthrange(year,month) Returns two integers. The first is the date code of the day of the week of the month, and the second is the day code of the month. Days range from 0 (Monday) to 6 (Sunday); months range from 1 to 12. |
8 |
calendar.prcal(year,w=2,l=1,c=6) is equivalent to print calendar .calendar(year,w,l,c). |
9 |
##calendar.prmonth(year,month,w=2,l=1) Equivalent to print calendar.calendar(year, w, l, c). |
10 |
calendar.setfirstweekday(weekday) Set the starting day code of each week. 0 (Monday) to 6 (Sunday). |
11 |
calendar.timegm(tupletime) The opposite of time.gmtime: accepts a time tuple form and returns the time The time of day (the number of floating point seconds elapsed since the 1970 epoch). |
12 |
calendar.weekday(year,month,day) Returns the date code of the given date. 0 (Monday) to 6 (Sunday). Months range from 1 (January) to 12 (December). |
Other related modules and functions
In Python, other modules for processing dates and times are:
datetime module
pytz module
dateutil module
|