Python入门系列(八)日期时间、数学、json

日期时间

Python中的日期本身不是数据类型,但我们可以导入一个名为datetime的模块,将日期作为日期对象使用。

import datetime

x = datetime.datetime.now()
print(x)

日期输出

import datetime

x = datetime.datetime.now()

print(x.year)
print(x.strftime("%A"))

创建日期对象

import datetime

x = datetime.datetime(2020, 5, 17)

print(x)

strftime()方法

import datetime

x = datetime.datetime(2018, 6, 1)

print(x.strftime("%B"))
DirectiveDescriptionExample
%aWeekday, short versionWed
%AWeekday, full versionWednesday
%wWeekday as a number 0-6, 0 is Sunday3
%dDay of month 01-3131
%bMonth name, short versionDec
%BMonth name, full versionDecember
%mMonth as a number 01-1212
%yYear, short version, without century18
%YYear, full version2018
%HHour 00-2317
%IHour 00-1205
%pAM/PMPM
%MMinute 00-5941
%SSecond 00-5908
%fMicrosecond 000000-999999548513
%zUTC offset+0100
%ZTimezoneCST
%jDay number of year 001-366365
%UWeek number of year, Sunday as the first day of week, 00-5352
%WWeek number of year, Monday as the first day of week, 00-5352
%cLocal version of date and timeMon Dec 31 17:41:00 2018
%CCentury20
%xLocal version of date12/31/18
%XLocal version of time17:41:00
%%A % character%
%GISO 8601 year2018
%uISO 8601 weekday (1-7)1

数学

min()和max()函数可用于查找可迭代中的最低或最高值

x = min(5, 10, 25)
y = max(5, 10, 25)

print(x)
print(y)

函数的作用是:返回指定数字的绝对(正)值

x = abs(-7.25)

print(x)

pow(x,y)函数将x的值返回到y(xy)的幂。

# Return the value of 4 to the power of 3 (same as 4 * 4 * 4)
x = pow(4, 3)

print(x)

数学模块

import math

x = math.sqrt(64)

print(x)

ceil()方法将一个数字向上舍入到其最接近的整数,然后进行数学运算。floor()方法将数字向下舍入到最接近的整数,并返回结果

import math

x = math.ceil(1.4)
y = math.floor(1.4)

print(x) # returns 2
print(y) # returns 1

pi常量,返回pi的值(3.14…)

import math

x = math.pi

print(x)

JSON

从JSON转换为Python

import json

# some JSON:
x =  '{ "name":"John", "age":30, "city":"New York"}'

# parse x:
y = json.loads(x)

# the result is a Python dictionary:
print(y["age"])

从Python转换为JSON

import json

# a Python object (dict):
x = {
  "name": "John",
  "age": 30,
  "city": "New York"
}

# convert into JSON:
y = json.dumps(x)

# the result is a JSON string:
print(y)

您可以将以下类型的Python对象转换为JSON字符串.

当您从Python转换为JSON时,Python对象将转换成JSON(JavaScript)等价物

PythonJSON
dictObject
listArray
tupleArray
strString
intNumber
floatNumber
Truetrue
Falsefalse
Nonenull

格式化结果

使用缩进参数定义缩进的数量

json.dumps(x, indent=4)

您还可以定义分隔符,默认值为(“,”,“:”,这意味着使用逗号和空格分隔每个对象,使用冒号和空格分隔键和值

json.dumps(x, indent=4, separators=(". ", " = "))

json_dumps()方法有参数来对resu中的键进行排序

json.dumps(x, indent=4, sort_keys=True)

正则表达式

Python有一个名为re的内置包,可用于处理正则表达式。

import re

正则表达式函数

FunctionDescription
findallReturns a list containing all matches
searchReturns a Match object if there is a match anywhere in the string
splitReturns a list where the string has been split at each match
subReplaces one or many matches with a string

元字符是具有特殊含义的字符

CharacterDescriptionExample
[]A set of characters“[a-m]”
\Signals a special sequence (can also be used to escape special characters)“\d”
.Any character (except newline character)“he…o”
^Starts with“^hello”
$Ends with“planet$”
*Zero or more occurrences“he.*o”
+One or more occurrences“he.+o”
?Zero or one occurrences“he.?o”
{}Exactly the specified number of occurrences“he.{2}o”
|Either or“falls|stays”
()Capture and group

特殊序列

CharacterDescriptionExample
\AReturns a match if the specified characters are at the beginning of the string“\AThe”
\bReturns a match where the specified characters are at the beginning or at the end of a word (the “r” in the beginning is making sure that the string is being treated as a “raw string”)r"\bain" r"ain\b"
\BReturns a match where the specified characters are present, but NOT at the beginning (or at the end) of a word (the “r” in the beginning is making sure that the string is being treated as a “raw string”)r"\Bain" r"ain\B"
\dReturns a match where the string contains digits (numbers from 0-9)“\d”
\DReturns a match where the string DOES NOT contain digits“\D”
\sReturns a match where the string contains a white space character“\s”
\SReturns a match where the string DOES NOT contain a white space character“\S”
\wReturns a match where the string contains any word characters (characters from a to Z, digits from 0-9, and the underscore _ character)“\w”
\WReturns a match where the string DOES NOT contain any word characters“\W”
\ZReturns a match if the specified characters are at the end of the string“Spain\Z”

集合是一对方括号[]内的一组字符,具有特殊含义

SetDescription
[arn]Returns a match where one of the specified characters (a, r, or n) is present
[a-n]Returns a match for any lower case character, alphabetically between a and n
[^arn]Returns a match for any character EXCEPT a, r, and n
[0123]Returns a match where any of the specified digits (0, 1, 2, or 3) are present
[0-9]Returns a match for any digit between 0 and 9
[0-5][0-9]Returns a match for any two-digit numbers from 00 and 59
[a-zA-Z]Returns a match for any character alphabetically between a and z, lower case OR upper case
[+]In sets, +, *, ., `

findall()函数的作用是:返回一个包含所有匹配项的列表。

import re

txt = "The rain in Spain"
x = re.findall("ai", txt)
print(x)

该列表按找到的顺序包含匹配项。
如果未找到匹配项,则返回空列表

import re

txt = "The rain in Spain"
x = re.findall("Portugal", txt)
print(x)

search()函数的作用是:在字符串中搜索匹配项,如果存在匹配项,则返回匹配对象。

import re

txt = "The rain in Spain"
x = re.search("\s", txt)

print("The first white-space character is located in position:", x.start())

split()函数的作用是:返回一个列表,其中字符串在每次匹配时被拆分

import re

txt = "The rain in Spain"
x = re.split("\s", txt)
print(x)

可以通过指定maxsplit参数来控制出现次数

import re

txt = "The rain in Spain"
x = re.split("\s", txt, 1)
print(x)

sub()函数的作用是:用您选择的文本替换匹配项

import re

txt = "The rain in Spain"
x = re.sub("\s", "9", txt)
print(x) # The9rain9in9Spain

您可以通过指定count参数来控制替换的数量

import re

txt = "The rain in Spain"
x = re.sub("\s", "9", txt, 2)
print(x)

匹配对象是包含有关搜索和结果的信息的对象。

注意:如果没有匹配,将返回值None,而不是match对象。

.span()返回包含匹配的开始位置和结束位置的元组。

import re

txt = "The rain in Spain"
x = re.search(r"\bS\w+", txt)
print(x.span()) # (12, 17)

.string 返回传递到函数中的字符串

import re

txt = "The rain in Spain"
x = re.search(r"\bS\w+", txt)
print(x.string) # The rain in Spain

.group() 返回字符串中存在匹配项的部分

import re

txt = "The rain in Spain"
x = re.search(r"\bS\w+", txt)
print(x.group()) # Spain
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值