python输入和输出

1. 输出格式化

使用字符串格式字面量,使用单引号或者(三倍单引号),在这个字符串当中,你可以使用Python表达式{},来关联变量,eg:

year = 2019

f'the year is {year}'

str.format方法是字符串的方法,可以提供更详细的格式化指令,但是 也需要被格式化的信息。eg:

 yes_votes=42_572_654

no_votes=43_132_495

percentage=yes_votes/(yes_votes+no_votes)

'{:-9} YES votes {:2.2%}'.format(yes_votes,percentage)

' 42572654 YES votes 49.67%'

2. 关于str和repr方法的内容见该链接:

https://blog.csdn.net/ysgjiangsu/article/details/75299883

3. 格式化的字符串字面量

可以通过“:”符号来设置字符的最小宽度,

'{name:10}' // 向左靠齐,最少10个字符

‘{name:10d}‘ // 向右靠齐,最少10个字符

更多内容见:https://docs.python.org/3/library/string.html#formatspec

4. str.format方法

看几个例子就懂了:

>>> print('{0} and {1}'.format('spam','eggs'))spam and eggs

>>> print('{1} and {0}'.format('spam','eggs'))eggs and spam

>>> print('This {food} is {adjective}.'.format(

... food='spam',adjective='absolutely horrible'))

This spam is absolutely horrible.

>>> table={'Sjoerd':4127,'Jack':4098,'Dcab':8637678}

>>> print('Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table))

Jack: 4098; Sjoerd: 4127; Dcab: 8637678

5. 读写文件 f=open('workfile','w')

格式获取文件的句柄,可以使用下列方式自动释放资源:

>>> withopen('workfile')asf:

... read_data=f.read()

>>> f.closedTrue

如果不使用此格式,则需要手动关闭 f.close()

具体api见文档

6. 使用json保存序列化数据(json模块)

json.dumps( [ 1, 'simple', 'list'])

json.dump(x, f) // f是打开的文件句柄,对x进行序列化并保存至f当中

json.load(f) // 对f当中的json数据进行反序列化

上述方法只是简单地对list和dictionaries进行处理,

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容