#1.4文件输入和输出 #读文件 f = open("/home/liulipeng/test.c") line = f.readline() while line: print line, # print(line, end='') line = f.readline() f.close() # readline()方法读取一行内容,包括结尾的换行符在内。 # 读至文件结尾时返回空字符串 for line in open("/home/liulipeng/test.c"): print line, #写文件 principal = 1000 rate = 0.05 numyears = 5 year = 1 f = open("out","w"); while year <= numyears: principal = principal * (1 + rate) #1) print >>f, "%3d %0.2f" % (year, principal) #2) #f.write("%3d %0.2f\n" % (year,principal)) #print("%3d %0.2f" % (year,principal),file=f) year += 1 f.close() #从文件sys.stdin读取,写入文件sys.stdout import sys sys.stdout.write("Enter your name:") name = sys.stdin.readline() name = raw_input("Enter your name:") #Python3 中raw_input()叫做input()
#####################################################################################
#1.5字符串 #1)创建字符串字面量 a = "Hello World!" b = 'Python is groovy' c = """Computer syas 'NO'""" print '''Content-type:text/html <h1> HelloWorld</h1> Click<a href="http://www.python.org">here</a> ''' #NOTE: #引号必须成对出现 #使用单引号和双引号指定的字符串必须在一个逻辑行上 #两个三引号之间出现的所有文本都视为字符串的内容 #2)提取字符串 a = "Hello World" b = a[4] #b = 'o' #切片运算符 s[i:j] i<= k < j c = a[:5] #c = "Hello" 从字符串的开始位置开始 d = a[6:] #d = "World" 到字符串的结尾位置 e = a[3:8] #e = "lo wo" #3)字符串的连接 g = a + "This is a test" x = "37" y = "42" z = x + y print z #z = "3742" #4)数学计算 int() float() z = int(x) + int(y) #z = 79(Inter +) #非字符串值转换为字符串表示形式 #str() repr() format() #str()和print()得到的输出相同 #repr()创建的字符串可以表示程序中某个对象的精确值 #format()函数的作用是利用特定格式将值转换成字符串 s = "The value of x is " + str(x) s = "The value of x is " + repr(x) s = "The value of x is " + format(x,"4d")