Python Python Python
Python
Python
Python
读取open.txt的内容,打印,然后把所有的‘Python’替换成‘Java’,最后去除所有的空格。
filename = 'open.txt'
with open(filename) as file_object:
lines = file_object.readlines()
ans = ''
for line in lines:
ans += line.strip()
print(ans)
ans = ans.replace('Python','Java')
print(ans)
#去空格
ans = ans.replace(' ','')
print(ans)
strip()只是去除两边的空格或者换行,然后lstrip()和rstrip()是分别取去除左边和右边的空格或者换行,注意文件每行的末尾都有一个换行符,strip可以去掉,但是不能去掉中间的空格。这里有四种方法,后三种还没看。先用replace直接替换第一种来的最暴力。