python基础
1、判断字符串是否为字母或数字
1) 用str.isdigit()函数判断是否数字
字符串中含有小数点、空格等其他字符时,返回False。
2) 用str.isalpha()判断是否字母
不区分大小写,含有除字母以外的字符则返回False
3) 用str.isalnum()判断是否数字和字母的组合
不区分大小写,含有除字母以外的字符则返回False,只含有数字或字母是True,同时含字母和数字返回True。
2、Python文本格式化
2.1使用百分号%
name = 'yyy'
age = 18
msg = '''
***information***
name: %s
age:%d
''' % (name, age)
print(msg)
2.2使用format(),大括号内可以通过序号表示要写入的信息
name = 'yyy'
age = 18
msg = '''
***information***
name: {}
age:{}
'''.format(name, age)
print(msg)
3、copy和deepcopy
import copy
res_df = copy.deepcopy(df)
深度复制时,修改原数据不会改变新复制的数据
4、python文件读写和异常
4.1 csv/文本文件
f.open()
open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True)
mode:打开文件的模式,r,w,a等
file_path = './file/df1.csv'
f = None
try:
f = open(file_path, 'r')
except FileNotFoundError as e:
print('未找到指定文件')
except UnicodeDecodeError as e:
print("读取文件时解码错误!")
except Exception as e:
print(e)
finally:
if f:
print(f.read())
f.close()
with open() as f:
不需要手动关闭文件,只能在with语句下进行操作,结束with语句时自动关闭文件。
with open(file_path, 'r') as f:
print(f.read())
按行读取
with open(file_path, 'r') as f:
for line in f:
print(line)
或:
lines = f.readlines()
for line in lines:
print(line)
4.2 json文件
import json
mydict = {
'name': 'yjx',
'age': 18,
'qq': 888,
'cars': [
{'brand': 'BYD', 'max_speed': 180},
{'brand': 'Audi', 'max_speed': 280},
{'brand': 'Benz', 'max_speed': 320}
]