10-2 C语言学习笔记:可使用方法replace()将字符串中的特定单词都替换为另一个单词。下面是一个简单的示例,演示了如何将句子中的'dog'替换为'cat':
with open(r'learning_python.txt') as file_object: for line in file_object: print(line.replace('Python','C').rstrip())
10-4 访客名单:编写一个while循环,提示用户输入其名字。用户输入其名字后,在屏幕上打印一句问候语,并将一条访问记录添加到文件guest_book.txt 中。确保这个文件中的每条记录都独占一行。
with open(r'guest_book.txt','w') as file_object: while(1): name = input("Input 'quit' to leave:") if(name=='quit'): break; print("Welcome, "+name.title()+".") file_object.write(name+'\n');
10-6 加法运算:提示用户提供的数值输入时,常出现的一个问题是,用户提供的是文本而不是数字。在这种情况下,当你尝试将输入转换为整数时,将引发ValueError异常。编写一个程序,提示用户输入两个数字,在将它们相加并打印结果。在用户输入的任何一个值不是数字时都捕获ValueError异常,并打印一条友好的错误消息。对你编写的程序进行测试:先输入两个数字,再输入一些文本而不是数字。
try: int1 = int(input("Please input a number:")) int2 = int(input("Please input a number:")) print(int1+int2) except ValueError: print("The type is not int.")
10-11 喜欢的数字:编写一个程序,提示用户输入他喜欢的数字,并使用json.dump()将这个数字存储到文件中。再编写一个程序,从文件中读取这个值,并打印消息"I know your favorite number!It's ___."
import json with open(r'number.txt','w') as file_obj: number = int(input("Please input your favorite number:")) json.dump(number,file_obj)
import json with open(r'number.txt') as file_obj: number = json.load(file_obj) print("I know your favorite number!It's "+str(number)+".")