您的位置:首页 > 编程语言 > Python开发

python学习基础之 字符串操作 和 I/O操作 以及条件与循环

2019-06-15 13:37 731 查看

字符串

字符串的声明
s1= ‘hello’
s2 = “hello”
s3 = “”“hello”""
print(s1s2s3) # True
字符串操作 切片 替换

  1. 索引
print(s1[0]) # h
  1. 切片
print(s1[1:3]) # el
  1. 替换
s = s.replace('h', 'H')  # 此时创建了一个新的字符串
  1. 拼接
s2 += s1 等同于 s2 = s2 + s1
  1. 遍历
for s in s1: # 像数组一样进行遍历
print(s)
  1. 格式化字符串 常用于日志输出
s = 'today weather is {} today is {}'.format('sunday', 'wonday')
print (s)  # today weather is sunday today is wonday
  1. 字符串拼接性能比较
t1 = time.perf_counter()
s = ''
for i in range(0,1000000):
s += str(i)
t2 = time.perf_counter()
print ('方式一耗费时间 {}'.format(t2-t1))  # 0.4358797559980303

t1 = time.perf_counter()
s = []
for i in range(0,1000000):
s.append(str(i))
s1 = ''.join(s)
t2 = time.perf_counter()
print ('方式二耗费时间 {}'.format(t2-t1))  # 0.37377301102969795

t1 = time.perf_counter()
s1 = ''.join(map(str, range(0, 1000000)))
t2 = time.perf_counter()
print ('方式三耗费时间 {}'.format(t2-t1))  # 0.2560606470797211

以上可以看出 方式3的性能最优 但是1和2 其实也很快了 在python2.5 版本以后 在拼接字符串方面 python 会检测当前字符串有没有其他的引用,如果没有就直接扩充字符串buffer的容量 不用再重新创建一个。所以以后可以放心使用。

I/O操作

这里只说最简单的也是用到最多 最方便的 with 语法 下面写一个具体的例子 对应的github 地址https://github.com/everyStudyNow/ml_learning.git

words = {}
with open('./test.txt', 'r') as f:  # 这种方式打开文件不需要考虑 关闭 更方便
lines = f.readlines()  # 读出所有行
for line in lines:
if line != '':
ls = line.split(' ')
for w in ls:
if w not in words:
words[w] = 1
else:
words[w] += 1  # 统计词频
sort_words = sorted(words.items(), key=lambda kv:kv[1], reverse=True)
print (sort_words)
with open('./test1.txt','w') as f:  # 文件权限
for k,v in sort_words:
f.write('{} {}\n'.format(k, v))

以上代码的执行结果就是对 test文件做词频统计 读写文件的方法很多 为什么这里只讲with语句 因为with语句不用考虑文件的关闭 用起来方便 如果考虑到性能问题 比如大文件的读入 可以使用生成器的方法来做,以后会讲。

JSON 序列化

主要用到两个函数 json.dumps()转换成json字符串 json.loads() 转化成json对象

params = {
'symbol': '123456',
'type': 'limit',
'price': 123.4,
'amount': 23
}

s = json.dumps(params)
print (type(s)) # <class 'str'>
s = json.loads(s)
print (type(s)) # <class 'dict'>

和文件结合使用 可以实现json字符串的直接写入

s = json.dumps(params)
print (type(s))
s = json.loads(s)
print (type(s))

with open('params.json', 'w') as fout:
params_str = json.dump(params, fout)

with open('params.json', 'r') as fin:
original_params = json.load(fin)

print('after json deserialization')
print('type of original_params = {}, original_params = {}'.format(type(original_params), original_params))

条件与循环

这里列举常用的if else 以及 列表 字典的遍历 和 break 和 continue关键字
if else 在列表和字典中的使用

  1. 列表
t = [2,3,4,1,5]
for i in t:
print(i) # 2 3 4 1 5
  1. 字典
t_dic = {'name':'晨光','age':18,'sex':'男'}
for t in t_dic:
print(t) #name age sex 只遍历出键

for t in t_dic.values():
print(t) # 晨光 18 男 只遍历出值

for k,v in t_dic.items():
print(k,v) # 键值一起遍历出
# name 晨光
# age 18
# sex 男
使用 in 可以判断出相应的键值在不在字典中
print('name' in t_dic) # True
print('test' in t_dic)  # False
print(18 in t_dic.values()) # True
  1. break && continue
t = [2,3,4,1,5]
for i in t:
if i == 3:
break
print(i) # 2
print()

for i in t:
if i == 3:
continue
print(i) # 2 4 1 5
print()
break 是 当条件满足时 跳出当前循环
continue 是 当条件满足时 跳过当前判断的循环  注意都是跳过

总结

学编程基础一定要打牢固 可以避免很多低级错误

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: