集成电路技术分享

 找回密码
 我要注册

QQ登录

只需一步,快速开始

搜索
查看: 2269|回复: 3

给深度学习入门者的Python快速教程基础篇之二十

[复制链接]
4798345 发表于 2017-5-23 17:07:47 | 显示全部楼层 |阅读模式
字符串
Python中字符串相关的处理都非常方便,来看例子:
a = 'Life is short, you need Python'
a.lower() # 'life is short, you need Python'
a.upper() # 'LIFE IS SHORT, YOU NEED PYTHON'
a.count('i') # 2
a.find('e') # 从左向右查找'e',3
a.rfind('need') # 从右向左查找'need',19
a.replace('you', 'I') # 'Life is short, I need Python'
tokens = a.split() # ['Life', 'is', 'short,', 'you', 'need', 'Python']
b = ' '.join(tokens) # 用指定分隔符按顺序把字符串列表组合成新字符串
c = a + '\n' # 加了换行符,注意+用法是字符串作为序列的用法
c.rstrip() # 右侧去除换行符
[x for x in a] # 遍历每个字符并生成由所有字符按顺序构成的列表
'Python' in a # True

Python2.6中引入了format进行字符串格式化,相比在字符串中用%的类似C的方式,更加强大方便:
a = 'I’m like a {} chasing {}.'
# 按顺序格式化字符串,'I’m like a dog chasing cars.'
a.format('dog', 'cars')

# 在大括号中指定参数所在位置
b = 'I prefer {1} {0} to {2} {0}'
b.format('food', 'Chinese', 'American')

# >代表右对齐,>前是要填充的字符,依次输出:
# 000001
# 000019
# 000256
for i in [1, 19, 256]:
print('The index is {:0>6d}'.format(i))

# <代表左对齐,依次输出:
# *---------
# ****------
# *******---
for x in ['*', '****', '*******']:
progress_bar = '{:-<10}'.format(x)
print(progress_bar)

for x in [0.0001, 1e17, 3e-18]:
print('{:.6f}'.format(x)) # 按照小数点后6位的浮点数格式
print('{:.1e}'.format(x)) # 按照小数点后1位的科学记数法格式
print ('{:g}'.format(x)) # 系统自动选择最合适的格式

template = '{name} is {age} years old.'
c = template.format(name='Tom', age=8)) # Tom is 8 years old.
d = template.format(age=7, name='Jerry')# Jerry is 7 years old.
fpga_feixiang 发表于 2017-6-3 10:22:40 | 显示全部楼层
看不懂呢,代码有点乱啊
辽工大小白 发表于 2017-12-24 22:29:37 | 显示全部楼层
这个确实很实用的,对于小白来说无异于雪中送炭
fpga_feixiang 发表于 2017-12-25 11:02:04 | 显示全部楼层
学习Python了
您需要登录后才可以回帖 登录 | 我要注册

本版积分规则

关闭

站长推荐上一条 /1 下一条

QQ|小黑屋|手机版|Archiver|集成电路技术分享 ( 京ICP备20003123号-1 )

GMT+8, 2024-4-19 12:40 , Processed in 0.073592 second(s), 19 queries .

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表