Python 读写文件
# Filename : test.py
# 写文件
with open("test.txt", "wt") as out_file:
out_file.write("该文本会写入到文件中\n 看到我了吧!")
# Read a file
with open("test.txt", "rt") as in_file:
text = in_file.read()
print(text)
执行以上代码输出结果为:
该文本会写入到文件中
看到我了吧!
Python 字符串判断
# 测试实例一
print("测试实例一")
str = "hello"
print(str.isalnum()) # 判断所有字符都是数字或者字母
print(str.isalpha()) # 判断所有字符都是字母
print(str.isdigit()) # 判断所有字符都是数字
print(str.islower()) # 判断所有字符都是小写
print(str.isupper()) # 判断所有字符都是大写
print(str.istitle()) # 判断所有单词都是首字母大写,像标题
print(str.isspace()) # 判断所有字符都是空白字符、\t、\n、\r
print("------------------------")
# 测试实例二
print("测试实例二")
str = "runoob"
print(str.isalnum())
print(str.isalpha())
print(str.isdigit())
print(str.islower())
print(str.isupper())
print(str.istitle())
print(str.isspace())
执行以上代码输出结果为:
测试实例一
False
False
False
True
False
False
False
------------------------
测试实例二
True
True
False
True
False
False
Python 字符串大小写转换
# Filename : test.py
str = "www.baidu.com"
print(str.upper()) # 把所有字符中的小写字母转换成大写字母
print(str.lower()) # 把所有字符中的大写字母转换成小写字母
print(str.capitalize()) # 把第一个字母转化为大写字母,其余小写
print(str.title()) # 把每个单词的第一个字母转化为大写,其
余小写
执行以上代码输出结果为:
WWW.BAIDU.COM
www.baidu.com
Www.baidu.com
Www.Baidu.Com
Python 计算每个月天数
#!/usr/bin/python3
import calendar
monthRange = calendar.monthrange(2016,9)
print(monthRange)
执行以上代码输出结果为:
(3, 30)
输出的是一个元组,第一个元素是所查月份的第一天对应的是星期几(0-6),
第二个元素是这个月的天数。以上实例输出的意思为 2016 年 9 月份的第一
天是星期四,该月总共有 30 天。
Python 获取昨天日期
# Filename : test.py
# 引入 datetime 模块
import datetime
def getYesterday():
today=datetime.date.today()
oneday=datetime.timedelta(days=1)
yesterday=today-oneday
return yesterday
# 输出
print(getYesterday())
执行以上代码输出结果为:
2023-01-08
以上实例输出的意思为昨天的日期是 2023年 1月 8日。