与我们从写字板之类的软件里看到的有不同的地方,'\n' 这就是出现异样结果的原因,readline每次会读到\n为止,把从开始读的地方的字符一直到‘\n’读取下来,并赋值给等号左边的变量words, 所以第一个words里的内容是“hello! www.jeapedu.com\n”, 第二次调用readline函数时,程序会从'P'开始读数据一直读到'a'后边的'\n'结束,因此第二个words里存储的是“Python professinal
trainning organization of China\n”,而每次print函数输出数据时都会自动加上一个'\n'(),故而会有两个'\n'被打印出来,所以会出现两个字符串间有一空行的结果。原因分析清楚了,那我们怎么解决这个问题呢?下面介绍一下字符串里的另外一个函数rstrip函数,这个函数的作用是去除字符串里指定字符。
rfile = open("a.txt", 'r')
words = rfile.readline()
words = words.rstrip('\n')
print words
words = rfile.readline()
words = words.rstrip('\n')
print words
rfile.close()
其结果如下所示
hello! www.jeapedu.com
Python professinal trainning organization of China 从结果可以看出两行输出的结果里已无多余的一行空格行输出了,这里我们通过使用string的rstrip函数去除了字符串最右侧的'\n'无用字符操作。
rfile = open("a.txt", 'r')
a = rfile.readline()
print a
b = rfile.readline()
print b
c = rfile.readline()
print c
d = rfile.readline()
print d
print a + b + c + d
rfile.close()输出结果为:
12
122
13
15
12
122
13
15
上边9~12行的输出结果为"print a + b + c + d"这条语句的输出结果,可以分析出此时的a、b、c、d为字符串数据,做“+”操作只是将字符串连接在一起而没有求和!怎么办呢?之前我们学习过int和float函数可以强制转换字符串为整形或者浮点型数据,我们来改一下上边的程序!
rfile = open("a.txt", 'r')
a = rfile.readline()
a = int(a)
print a
b = rfile.readline()
b = int(b)
print b
c = rfile.readline()
c = int(c)
print c
d = rfile.readline()
d = int(d)
print d
print a + b + c + d
rfile.close()