首页  

python3-006 输入输出     所属分类 python 浏览量 451
str()   返回一用户易读的表达形式
repr()  返回解释器易读的表达形式

输出 平方与立方表

for x in range(1,11):
  print(repr(x).rjust(2),repr(x*x).rjust(3),repr(x*x*x).rjust(4))

 rjust() 方法, 靠右, 左边填充空格


 1   1    1
 2   4    8
 3   9   27
 4  16   64
 5  25  125
 6  36  216
 7  49  343
 8  64  512
 9  81  729
10 100 1000


 ljust()  center()
 zfill(), 数字的左边填充 0
'12'.zfill(5)
'-3.14'.zfill(7)
'3.1415926'.zfill(5)

str.format() 

print("name={},age={}".format("tiger",3))
print("name={0},age={1}".format("tiger",3))
print("name={name},age={age}".format(name="tiger",age=3))

print("name={0},age={1},nick={nick}".format("tiger",3,nick="kitty"))

旧式字符串格式化
import math
print("PI=%2.3f" % math.pi)
print("name=%s,age=%s" % ("tiger",3))


读取键盘输入
input() 内置函数从标准输入读入一行文本

line = input()
print("your input:",line)

读写文件
open(filename,mode)

r	只读 , 文件指针放在文件的开头 ,默认模式
r+	读写 , 文件指针放在文件的开头
w	写入 ,如果文件已存在则打开文件,并从开头开始写,原有内容会被删除 , 如果文件不存在,创建新文件
w+	读写 ,其他同 w 
a	追加 ,如果该文件已存在,文件指针放在文件的结尾,文件不存在,创建新文件 
a+	读写 ,其他同 a 


f = open("/tmp/hello.txt","w")
f.write("hello \n python\n")
f.close()

f = open("/tmp/hello.txt","r")
contents = f.read()
f.close()

f = open("/tmp/hello.txt","r")
line = f.readline()
f.close()

f.readline() 如果返回一个空字符串, 说明已经已经读取到最后一行

f = open("/tmp/hello.txt","r")
lines = f.readlines()
f.close()
for line in lines :
  print(line)

f.tell()
返回当前所处的位置, 从文件开头开始算起的字节数

f.seek()
改变文件当前位置
f.seek(offset, from_what) 
from_what  
0 开头
1 当前位置
2 文件的结尾
默认0,即文件开头

seek(x,0)    从文件头移动 x 个字节
seek(x,1)    从当前位置往后移动x个字节
seek(-x,2)   从文件的结尾往前移动x个字节


with open("/tmp/hello.txt","r") as f:
  contents = f.read()
  print(contents)

with  自动关闭文件

上一篇     下一篇
python3-004 迭代器和生成器

python3-005 函数

python3 str 内置函数调用错误

python3-007 错误和异常

docker search 查看版本

docker 安装 centos7