签到成功

知道了

CNDBA社区CNDBA社区

Python第13天--输入和输出

2021-11-06 21:44 841 0 原创 Python
作者: hbhe0316

如果我们想要将输出的值转成字符串,可以使用 repr() 或 str() 函数来实现,其中 repr() 函数产生一个解释器易读的表达形式,str() 函数返回一个用户易读的表达形式。

http://www.cndba.cn/hbhe0316/article/5045
http://www.cndba.cn/hbhe0316/article/5045

如果我们不只是想打印使用空格分隔的值,而是想对输出进行格式化控制,可以采用两种方式:一种是自己处理整个字符串,另一种是采用 str.format() 方式,下面介绍下 str.format() 的使用。http://www.cndba.cn/hbhe0316/article/5045

s = 'Hello World.'
print(str(s))
str = input("请输入:");
print ("输入的内容是: ", str)

http://www.cndba.cn/hbhe0316/article/5045http://www.cndba.cn/hbhe0316/article/5045

读取文件

http://www.cndba.cn/hbhe0316/article/5045

[root@ansible home]# cat tmp.txt 
Hello World
[root@ansible home]# cat read.py 
f = open('tmp.txt', 'r')
str = f.read(12)
print(str)
f.close()
[root@ansible home]# python read.py 
Hello World

读取1行

[root@ansible home]# cat tmp.txt 
Hello World
[root@ansible home]# cat read.py
f = open('tmp.txt', 'r')
str = f.readlines()
print(str)
f.close()
[root@ansible home]# python read.py 
['Hello World/n']

write(string) 将 string 的内容写入文件。http://www.cndba.cn/hbhe0316/article/5045http://www.cndba.cn/hbhe0316/article/5045http://www.cndba.cn/hbhe0316/article/5045http://www.cndba.cn/hbhe0316/article/5045

[root@ansible home]# python write.py 
None
[root@ansible home]# cat tmp.txt 
Hello Python[root@ansible home]# cat write.py 
f = open('tmp.txt', 'w')
num = f.write('Hello Python')
print(num)
f.close()

版权声明:本文为博主原创文章,未经博主允许不得转载。

Python

用户评论
* 以下用户言论只代表其个人观点,不代表CNDBA社区的观点或立场
hbhe0316

hbhe0316

关注

1.只有承认无知,才能装下新的东西; 2.进步来自一点点滴滴的积累; 3.广博让你更优秀,而专业让你无法替代; 4.挫折和失败能够转换为一种财富。

  • 889
    原创
  • 1
    翻译
  • 13
    转载
  • 24
    评论
  • 访问:1038751次
  • 积分:1523
  • 等级:核心会员
  • 排名:第6名
精华文章
    最新问题
    查看更多+
    热门文章
      热门用户
      推荐用户
        Copyright © 2016 All Rights Reserved. Powered by CNDBA · 皖ICP备2022006297号-1·

        QQ交流群

        注册联系QQ