手机版
你好,游客 登录 注册 搜索
背景:
阅读新闻

Python起步之print & input用法总结

[日期:2013-06-11] 来源:Linux社区  作者:kiritor [字体:大 中 小]

3、输出字符串

>>> print ("%.4s " % ("hello world"))
hell

>>> print("%5.4s" %("Hello world"))
Hell

这里输出结果为“ Hello”,前面有一个空格

同样对其具体的输出格式也可以写成如下的形式

>>> print("%*.*s" %(5,4,"Hello world"))
Hell

这里对Python的print字符串格式输出形式

%A.Bs:A表示输出的总的字符串长度

B表示要输出字符串从开始截取的长度

A<B的时候,输出字符串长度为B(A可以<0 )

A>B的时候前方空格

B>字符串长度时,后面不用空格占位

4、输出浮点数(float)

>>> print("%10.3f" % 3.141516)
3.142

浮点数的输出控制和字符串相似,不过序注意的是.3表示的输出3位小数,最后一面按四舍五入方式进位。

input函数

了解了输出函数之后我们来看看输入函数input,同样的我们先在交互式解释器中查看input函数的具体情况。

input(...)
input([prompt]) -> string

Read a string from standard input. The trailing newline is stripped.
If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.
On Unix, GNU readline is used if enabled. The prompt string, if given,
is printed without a trailing newline before reading.

>>>

注意这里笔者的Python是3.3的,根据上面的描述可以很清楚的看到,input函数是从标准输入流读取一个字符串,注意换行符是被剥离的。input可以有一个参数,用来提示输入信息的,下面具体例子:

>>> name = input("your name is:")
your name is:kiritor
>>> print(name)
kiritor
>>>

查看官方文档我们可以更清楚的明白input是如何工作的。

If the prompt argument is present, it is written to standard output without a trailing newline.
&nbsp;The function then reads a line from input, converts it to a string (stripping a trailing newline),
and returns that. When EOF is read, EOFError is raised. Example:

ok,对于Python的输入输出就总结到这里了!

linux
相关资讯       Python print用法  Python input 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款