博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python输入和输出
阅读量:7199 次
发布时间:2019-06-29

本文共 1348 字,大约阅读时间需要 4 分钟。

格式化输出:

  print()

  write()

  sys.stdout

 

值转化成字符串:

  repr():

    转化为供解释器读取的形式

  str():

    转换为供人读取的形式

 

#将字符串输出到一列,并向左侧填充空格以右对齐,同理还有str.ljust,str.center()

str.rjust()

#向数值的字符串表达式填充0

>>> '12'.zfill(5)

'00012'

 

#.format基础用法‘{}’占位

>>> print('We are the {} who say "{}!"'.format('knights', 'Ni'))

We are the knights who say "Ni!"

#关键字参数

print('This {food} is {adjective}.'.format(food='spam', adjective='absolutely horrible'))

#位置参数和关键字参数可以随意组合

print('The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred',other='Georg'))

 

#'!a' (应用 ascii()),'!s' (应用 str() )和 '!r' (应用 repr() )可以在格式化之前转换值:

>>> import math

>>> print('The value of PI is approximately {}.'.format(math.pi))

The value of PI is approximately 3.14159265359.

>>> print('The value of PI is approximately {!r}.'.format(math.pi))

The value of PI is approximately 3.141592653589793.

 

# {:} ':' 指令允许对值的格式化加以控制

>>> import math

>>> print('The value of PI is approximately {0:.3f}.'.format(math.pi))

#对较长的字符串用命名引用    

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

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

 

#%格式化法

>>> import math

>>> print('The value of PI is approximately %5.3f.' % math.pi)

 

 

#>>> print('We are the {} who say "{}!"'.format('knights', 'Ni'))We are the knights who say "Ni!"

转载于:https://www.cnblogs.com/IMWU/p/9511584.html

你可能感兴趣的文章
MyCAT部署及实现读写分离(转)
查看>>
多个(子)进程的开启,进程的常用属性和方法
查看>>
netty入门05
查看>>
python 局部变量和全局变量
查看>>
CSS样式
查看>>
【Shell】使用shell打印菜单,一键安装Web应用
查看>>
ASP.NET Json数组的反序列化
查看>>
Git服务器Gogs简易安装-Windows环境
查看>>
BZOJ-1602: [Usaco2008 Oct]牧场行走 (LCA炒鸡大裸题)
查看>>
git pull --rebase 做了什么? 以及 Cannot rebase: You have unstaged changes 解决办法
查看>>
Mashup 理解 && paper:SmashQ
查看>>
leetcode之Invert Binary Tree
查看>>
js 根据身份证号获取性别,年龄,等
查看>>
PHP----实现压缩HTML
查看>>
xml 帮助类
查看>>
Webpack【1】 入门
查看>>
Hadoop、Spark 集群环境搭建问题汇总
查看>>
数据系列:通过Windows Azure SQL数据库防火墙规则控制数据库访问
查看>>
C++嵌套类
查看>>
推荐算法——非负矩阵分解(NMF)
查看>>